我有一个角色类定义为:
class Role < ActiveRecord::Base
include Filterable
has_and_belongs_to_many :users
end
可过滤模型关注的是:
module Filterable
extend ActiveSupport::Concern
module ClassMethods
def filter(filtering_params)
results = self.where(nil) # create an anonymous scope
filtering_params.each do |key, value|
results = results.public_send(key, value) if value.present?
end
results
end
end
end
结果 = self.where(nil) 行,返回所有角色
Role Load (1.1ms) SELECT "roles".* FROM "roles"
#<Role:0x007fd22d235080>
#<Role:0x007fd22d234ea0>
#<Role:0x007fd22d234cc0>
但是 results.public_send(key, value) 行会引发错误:
results.public_send(key, value)
*** NoMethodError Exception: undefined method `company' for # <Role::ActiveRecord_Relation:0x007fd232499da8>
如果我检查:
byebug) results.first
#<Role:0x007fd22d235080>
(byebug) results.first.inspect
#<Role id: 1, company: "internal", group: "accounting", function:
"employee", activities: {}, created_at: "2015-09-16 06:54:19",
updated_at: "2015-09-16 06:54:19">
(byebug) results.first.company
# nothing returned !
(byebug) results.first[:company]
internal
The Role class doesn't need any attribute accessor as it's an ActiveRecord class... the company, group, function should ahem getter/setter defined .. where am I wrong ?
感谢您的反馈