user984621
user984621

Reputation: 48463

Rails 4 - how to fetch all "belongs_to" for an object?

I have this scheme:

class Car < ActiveRecord::Base
  belongs_to :owner
end
class Owner < ActiveRecord::Base
  has_many :cars
end

I fetch all cars that has been added between certain dates, like:

@cars = Car.where("... from-to condition ...")

What I am trying to get: a unique list of all owners from @cars, in the best way like owners.email + owners.id. I've tried to do

puts @cars.owner.pluck(:id, :email).inspect

But this results into following error:

undefined method `owner' for #<ActiveRecord::Relation::...

How to get a list of all owners of the selected cars?

Thank you.

Upvotes: 2

Views: 1836

Answers (4)

Mike Manfrin
Mike Manfrin

Reputation: 2762

You're coming at this from the wrong side. You're trying to find Owners, so start there:

Owner

Now you add a joins, since you're trying to find owners whose cars meet some criteria:

Owner.joins(:car)

then add your where:

Owner.joins(:car).where(cars: {>your conditions<})

then add a distinct since in some cases you can have an owner who has multiple cars that match:

Owner.joins(:car).where(cars: {>your conditions<}).distinct

And then if you just want the id/email, you can pluck:

Owner.joins(:car).where(cars: {>your conditions<}).distinct.pluck("owner.id, owner.email")

Upvotes: 4

spickermann
spickermann

Reputation: 106952

You should also use distinct to avoid users that have multiple cars to be listed multiple times:

Car.where(condition: 'something').
   joins(:owner).
   pluck('DISTINCT owners.id, owners.email')

Upvotes: 0

user4092233
user4092233

Reputation: 63

Car.where("... from-to condition ...").joins(:owner).distinct.pluck('owners.id', 'owners.email')

EDIT: Fixed pluck.

Upvotes: 0

Pitabas Prathal
Pitabas Prathal

Reputation: 1012

Try this:

puts @cars.joins(:owner).pluck("owner.id, owner.email")

Upvotes: 3

Related Questions