0

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?!

2 Answers2

1
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.

manoj
  • 1,655
  • 15
  • 19
  • I get a syntax error at the Not keyword and at the last closing parenthesis. /app/controllers/producers_controller.rb:6: syntax error, unexpected tCONSTANT, expecting ')' ...here( "clients.producer.id" Not => "products.producer_id") ... ^ /app/controllers/producers_controller.rb:6: syntax error, unexpected ')', expecting keyword_end ... Not => "products.producer_id") ... ^ – Kostas Georgokitsos Apr 12 '13 at 10:52
  • ok this doesn't cause a syntax error, but blows up because I did not mention that both client and producer are subclasses of contact in a single table inheritance... Sorry. I have to do some kind of self join with different type attributes (one producer one client). – Kostas Georgokitsos Apr 12 '13 at 13:07
1
@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 !

Prem
  • 5,844
  • 3
  • 25
  • 23