How can I use eager loading with scope in complicated nested association?
I have 4 models such as below
User (has 1 profile, many communities, and many codes)
Profile (belongs to user)
Community (has many codes, belongs to user)
Code (belongs to both community and user)
Now I'm trying to show 10 records of the code that belongs to particular
community.
This code contains external table's info such as
username(in user table)
comment(in profile table)
point(in profile table)
Now, it's issuing many sql queries because I'm not using eager loading.
In this case, how can I customize my code to make this eager loading in
order to make load speed faster?
controllers/communities_controller.rb
#CanCan load_and_authorize_resouce
load_and_authorize_resource :find_by => :community_name,
models/community.rb
belongs_to :user
has_many :codes
models/code.rb
belongs_to :user, counter_cache: true
belongs_to :community, counter_cache: true
scope :recent, lambda { |n = 10| includes(:user).where('users.deleted_at'
=> nil).order("users.last_active_at DESC").limit(n) }
models/user.rb
has_one :profile
has_many :communities
has_many :codes
models/profile.rb
belongs_to :user
views/communityes/show.html.erb
<% @community.codes.recent.each do |code| %>
<%= render 'codes/code', {:code => code, :icon_photo =>
code.user.profile.user_avatar} %>
<% end %>
views/communityes/_code.html.erb
<tr>
Username: <%= code.user.username %> <br />
Code: <%= code.data %> <br />
Comment: <%= code.user.profile.comment %> <br />
Point: <%= code.user.profile.point.to_s %>
</tr>
No comments:
Post a Comment