0
st = 'pen'
ak = '123123'
agreements = Client.where{authentication_key == ak}.first.agreements
products = Product.joins{agreements}.where{agreements.id.in(a) & (short_description.like(st) | long_description.like( st))}

I am trying with the above but I need the matched agreement in my result set too..

Because of this

class Product < ActiveRecord::Base
  has_and_belongs_to_many :agreements, uniq: true

I cant use products.first.agreement.first.... That could be a different agreement.

Boti
  • 3,275
  • 1
  • 29
  • 54
  • This is the closest: Product.joins{agreements}.where{agreements.id.in(a) & (short_description.like(st) | long_description.like( st))}.select{[agreements.agreement_type, id]} But instead of id I want everything from product – Boti Feb 25 '13 at 18:06

1 Answers1

0

I'm not sure if this is exactly what you need, but hopefully it will be:

client = Client.where { authentication_key == ak }.first
products = Client.agreements.joins { products }.where { (short_description.like(st) | long_description.like(st) }

This returns the products associated with the agreements which are, in turn, associated to your client. If you need to get one client's agreements for a product, you could write a scope:

class Product < ActiveRecord::Base
  #...
  def self.agreements_for_client(id)
    joins { agreements }.where { client_id.eq(id) }
  end
end

and the call it:

client = Client.where { authentication_key == ak }.first
Product.first.agreements_for_client(client.id)

I hope this helps.

Andre Bernardes
  • 1,623
  • 12
  • 11