Galaxy
Galaxy

Reputation: 3400

Active Records - Where conditions on a has_one model?

If I have the following has_one setup:

class Account
 has_one :user

How can I do something like @account.user.where(:visible => true)

Or more specifically, how do I call conditions on a has_one relationship in a similar way to a has_many? I'm currently using a scope on the user which seems silly?

def is_visible?
  if self.visible
    return self 
  else
    return false
end

Upvotes: 0

Views: 118

Answers (1)

x1a4
x1a4

Reputation: 19485

You'll need to use a join to get the list of visible user accounts, but it's not too hard once you grok the query. Try this:

@accounts = Account.joins(:user).where(:users => {:visible => true})

You could also easily encapsulate it into a scope.

scope :with_visible_user, joins(:user).where(:users => {:visible => true})

@accounts = Account.with_visible_user

Upvotes: 1

Related Questions