Tuesday 15 March 2011

activerecord - Rails 4 query a reference via n:n relation -



activerecord - Rails 4 query a reference via n:n relation -

following structure

production belongs_to :offer has_many :production_positions has_many :products, through: :production_positions product has_many :production_positions has_many :productions, through: :production_positions productionposition belongs_to :production belongs_to :product

now want offers contains product_id 1. how did have query database?

to productions quite easy:

production.includes(:products).where("products.id" => 1)

but how offers referenced?

offer.includes(:production).includes(:products).where("products.id" => 1)

the line above produces next error: association named 'products' not found on offer

add has_many :products, through: :production in offer class , seek following:

offer.select('offers.*').joins(:products).where('products.id = ?', 1)

i assumed had has_one :production in offer class. add together scope perform query:

class offer < activerecord::base has_one :production has_many :products, through: :production scope :with_product_id, ->(id) select('offers.*'). joins(:products). where('products.id = ?', id) end end

example (offers product 1):

offer.with_product_id(1)

activerecord ruby-on-rails-4

No comments:

Post a Comment