pingu
pingu

Reputation: 8827

Specifying conditions on a relationship in Ruby on Rails

I have the following

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

and it works fine, but instead of using the 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"}}

Upvotes: 2

Views: 1249

Answers (2)

pingu
pingu

Reputation: 8827

Figured it out:

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

Upvotes: 2

colinross
colinross

Reputation: 2085

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?

Upvotes: 0

Related Questions