Tom Prats
Tom Prats

Reputation: 7911

DB query from a belongs_to relationship

I have a model: Animal

belongs_to :owner

I have a model: Owner

has_many :animals

Owner has a boolean attribute active

def self.not_active
  where('owner.active == ?', false)
end

The above code does not work for some reason. I've tried lots of things around it, but keep getting errors. When calling something like Animal.first.owner.active I get back either true or false, but the database call must be different...

For clarification I want the Animals for which their owner is not active. I don't want to do the opposite call though (Starting with the owner db and checking active and returning animals) because of calls I'm linking together off of Animal

Upvotes: 0

Views: 55

Answers (1)

Carlos Drew
Carlos Drew

Reputation: 1633

Your code should be:

def self.not_active
  includes(:owner).where("owners.active = ?", false)
end

When referencing a model in pure SQL, as you are doing so above, you need to use the table name, not the singular model name. Thus, owners, not owner.

A clearer style would be:

def self.not_active
  includes(:owner).where(owners: {active: false})
end

Rails AREL will take care of referencing the active attribute in the query correctly, and you don't have to worry about the exact table/model name.

Upvotes: 1

Related Questions