Reputation: 5197
I have 4 models such as below
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>
Upvotes: 1
Views: 1690
Reputation: 7978
Shouldn't be particularly complicated, just .includes
all the bits you want to eager load ..
@community.codes.recent.includes(user: :profile)
Also, are a Community
's codes always equal to that of all of it's User
s? If so, you should be using a has_many :codes, through: :users
association on Community
.
Upvotes: 1