开发者

Checking role in has-many relationship

开发者 https://www.devze.com 2023-03-06 12:17 出处:网络
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).

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

精彩评论

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