David
David

Reputation: 7456

Include extra rows in a has_many through relation

I'm not sure what the best way to tackle this is.

I have a has_many through relation:

class User < ActiveRecord::Base

  has_many :animals,
           through: :farms

end

My issue deals with wanting to add in an extra farm from which to include animals even though technically the user does not own that farm.

If the user has 10 farms with ids ranging from 1 to 10, then what I want is to do something like include a farm with id 15 also.

So where as one would usually do user.animals. I'd like to do something like user.animals.include("farms.id = ?", 15) which would give results of the animals in all the users farms (1 - 10) and also include the animals from farm 15.

How would I accomplish this?

Eventually my queries look like user.animals.reorder(created_at: :desc).includes(:owner, :farm).page(5).per(30).to_a

What is the best way to include other farms in the query?

Upvotes: 0

Views: 40

Answers (1)

Albin
Albin

Reputation: 3012

You could add the following method to your user model:

def animals_with_extra_farms(farm_ids = [])
  farm_ids += farms.map(&:id)
  Animal.where(farm_id: farm_ids)
end

Not that this will result in 2 database queries. There are other solutions that might be better from a performance point of view but this solution is very straight forward and easy to understand. And in my view easy code can be worth a few ms of performance.

If it turns out that this is a bottleneck you can always refactor it later.

Upvotes: 1

Related Questions