Rails 4 - Add scope to included Model -


i have association

class product   has_many :categorizations   has_many :categories, through: :categorization    scope :first_five, lambda { limit(5) } end  class category   has_many :categorizations   has_many :products, through: :categorization end 

for each category, want first 5 products using first_five scope defined above.

to minimize db request, use includes()

@categories = category.includes(:products).all 

but how add scope products? don't want use default_scope since affects everything.

i can't find on google (or can't right search term it)

thanks

the new syntax lambda scope in rails 4 is:

scope :first_five, -> { limit(5) } 

to limit 5 products in ar query, do:

@categories = category.includes(:products).merge(product.first_five).all 

the merge(product.first_five) going add left outer join on limited 5 products.

update:

the above code commented going limit categories. possible solution original problem add has_many...through relation calling limited_products on category model as:

has_many :limited_products, -> { limit(5) },           through: :products,           source: :categorizations 

with categeory.includes(:limited_products) should yield expected result of limiting products 5.

as you've suggested, add source: :categorizations option newly added association limited_products. source , class_name should have been synonymous. since association defining has_many...through association ignores class_name option, should using :source option instead of :class_name option. other association options ignored in has_many...through relation :primary_key , :foreign_key.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -