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

Using ActiveSupport::Concern and create accessors and validations dynamically

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

所以我有一个class(在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)

我猜你需要这样的东西:

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)

我更新了我的答案。