PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How to specify eager loading of associations in rails model

 October 21, 2022     eager-loading, has-many, ruby-on-rails     No comments   

Issue

class A < ActiveRecord::Base
  has_many :Bs
  has_many :Cs
  ...
end

I wish to load all of B's and C's whenever I do a query on A, say A.where(name: :abc), with a single query, instead of multiple calls to database.

I don't wish to specify .includes for every query I run. How do I specify eager loading in the model itself?

I looked many similar question and tried do this but it does not work:

default_scope :include => [:Bs, :Cs]

Solution

default_scope { includes(:Bs, :Cs) } should do it.

As far as I know the scope takes a block as argument not a hash of options. I just tried it in the rails console and seems to work.



Answered By - nbermudezs
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing