Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails where() clause on model association?

Suppose I have an Account model which has_many Users. Accounts have a boolean "active" column. How can I get all Users that belong to "active" accounts?

@users_of_active_accounts = User.? 

Thanks!

like image 650
Derek J Avatar asked Jun 13 '11 18:06

Derek J


People also ask

What does where return in Rails?

where returns an ActiveRecord::Relation (not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation. find (and its related dynamic find_by_columnname methods) returns a single model object.

What is difference between Has_one and Belongs_to?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user .

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is Activemodel?

Active Model is a library containing various modules used in developing classes that need some features present on Active Record.


2 Answers

Try this:

User.joins(:account).where(:accounts => { :active => true }) 
like image 60
Dogbert Avatar answered Sep 21 '22 12:09

Dogbert


You need to join the accounts table and merge appropriate Account scope:

User.joins(:account).merge(Account.where(:active => true)) 
like image 41
Simon Perepelitsa Avatar answered Sep 22 '22 12:09

Simon Perepelitsa