`
wudixiaotie
  • 浏览: 132856 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Rails里ActiveRecord里字段自动生成的实现。

阅读更多
class Base
	#定义inherited这个hook,当Base类被model类继承的时候就执行
	def self.inherited(model)
		arr_attr_name = %w{id title body create_by}#这里可以取得model的名字,再到数据库中去查询

		arr_attr_name.each do |attr_name|
			model.class_eval {attr_accessor attr_name}#给model类添加方法
		end
	end
end

class Post < Base
end

post = Post.new
post.id = 1
puts post.id

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics