Search code examples
ruby-on-railsjoinconditional-statementsrelationships

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"}}

Solution

  • Figured it out:

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