每个用户都有很多角色;找出用户是否具有“管理员”的角色,我们可以使用has_role?
方法:将`is_x?`混叠到`has_role? x`
some_user.has_role?('admin')
它是这样定义的:
def has_role?(role_in_question)
roles.map(&:name).include?(role_in_question.to_s)
end
我希望能够写some_user.has_role?('admin')
作为some_user.is_admin?
,所以我所做的:
def method_missing(method, *args)
if method.to_s.match(/^is_(\w+)[?]$/)
has_role? $1
else
super
end
end
也能正常工作的情况下some_user.is_admin?
,但是当我尝试CA失败将其放在另一个关联中引用的用户上:
>> Annotation.first.created_by.is_admin?
NoMethodError: undefined method `is_admin?' for "KKadue":User
from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.4/lib/active_record/associations/association_proxy.rb:215:in `method_missing'
from (irb):345
from :0
什么给出了?
详细说明,您需要重写'respond_to?'以完成此项工作。 – rfunduk 2010-07-21 19:30:31