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!
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.
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 .
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.
Active Model is a library containing various modules used in developing classes that need some features present on Active Record.
Try this:
User.joins(:account).where(:accounts => { :active => true })
You need to join the accounts table and merge appropriate Account scope:
User.joins(:account).merge(Account.where(:active => true))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With