每個用戶都有很多角色;找出用戶是否具有「管理員」的角色,我們可以使用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