开发者

Specifying conditions on a relationship in Ruby on Rails

开发者 https://www.devze.com 2023-03-08 17:06 出处:网络
I have the following has_many :administrators, :class_name => \"User\", :conditions => \"role_id = 4\"

I have the following

has_many :administrators, :class_name => "User", :conditions => "role_id = 4"

and it works fine, but instead of using th开发者_开发问答e foreign key

"role_id = 4"

I would prefer to specify the actual role string in the roles table, that that foreign key relates to, e.g "Admin"

UPDATE:

SELECT *
FROM users u, roles r
WHERE u.role_id = r.id
AND r.role = "Admin"

UPDATE 2

can't I do something like this: (this doesn't work, but illustrates what I am trying to do)

has_many :administrators, :class_name => "User", :conditions => { :role => {:name => "Admin"}}


Figured it out:

has_many :administrators, :class_name => "User", :conditions => {:roles => {:name => "Admin"}}, :include => :role


what about trying

has_many :administrators, :class_name => "User", :conditions => "role_id = #{Role.find(:name => 'Admin')}" 

Assuming the role table had a corresponding model. are you using a specific framework, or home baked authorization?

0

精彩评论

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