使用ActiveSupport :: Concern并动态创建访问器和验证

时间:2015-01-04 19:01:55

标签: ruby-on-rails

我想使用ActiveSupport::Concern来动态扩展ActiveRecord::Base功能。

所以我有一个班级(app/models/foo.rb

class Foo < ActiveRecord::Base

end

并在lib/activ_record_extention.rb我有

module ActiveRecordExtension

extend ActiveSupport::Concern

    module ClassMethods

       c= atrr_name
       attr_accessible c.to_sym



    end 

end

 ActiveRecord::Base.send(:include, ActiveRecordExtension)

但是当我运行服务器时,我得到了:

undefined method `attr_accessible' for ActiveRecord Extension:Module (NoMethodError)

1 个答案:

答案 0 :(得分:1)

我猜你需要这样的东西:

module ActiveRecordExtension
  extend ActiveSupport::Concern

  included do
    attr_accessible # Still need to call the API method

    def mass_assignment_authorizer
      # Here we can access object's attributes
      super << some_attr 
    end
  end 
end

ActiveRecord::Base.send(:include, ActiveRecordExtension)

我更新了我的答案。