문제

I am rather new to rails, so I ask for your patience.

I have a bit of an intricate relationship between three (ActiveRecord) models:

class Producer
  has_many :clients
end  

class Client
  belongs_to :producer
  has_many   :products
end

class Product
  belongs_to :client
  belongs_to :producer
end

The producer of a particluar product is not necessarily the same as the producer of the products client (but he can be).

I need to somehow select/scope all the products of a producer, where he is not the producer of that products client . I cannot wrap my head around that. I am trying to think in the line of producer != producer.products.clients.producer which of course doesn' work or make sense.

Please help?!

도움이 되었습니까?

해결책

Product.includes(:producer, :client).
   where("products.producer_id" => X).
   where( "clients.producer.id != products.producer_id")

will find the products from producer with id X as you wanted.

다른 팁

@products = Product.select("products.*").joins(:clients).joins(:producers).where("products.producer_id = ? AND clients.producer_id != ?", producer_id, producer_id)

should give you the required result.

Hope it helps !

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top