开发者

Checking role in has-many relationship

Using Cancan so I need to check a users roles. Have a has_many relationship with Users -> userroles(reference id's) -> roles(name of each role, with the role being in the name column).

In my user model I have a function: role?(role), i开发者_JS百科e role?(:admin), that checks to see if the user has a role.

def role?(role)
   roles.include? role.to_s
end

This doesn't work, do I have to specify the name column?

Solved: I'll put the answer down after the time elapses.


You're comparing a string to an object

def role?(role)
  !roles.first(:conditions => {:name => role.to_s}).nil?
end

Try this?

Alternative based on Dmitriy Likhten's answer

def role?(role)
  roles.collect{|r| r.name }.include? role.to_s
end


You can always just filter it in-line...

roles.select(&:to_s).include?(role.to_s)

The difference between mine and Jimmy's approach is dependent on whether or not the role is already in memory. If it is, filtering is faster, if not a query is better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜