her
her copied to clipboard
Has many associations load very slow when rendering from the view
When trying to use has many relations for a model , the page loads increases drastically.
Consider this example -
class Post
include Her::Model
has_many :comments
has_many :attachments
attributes :title, :status
In the controller the same is fetched like
@posts = Post.all
In the view -
# Assume there are 20 posts in the result
<% @posts.each do |post| %>
<%= @post.title %> #First level attribute
<% @posts.comments.each do |comment| %>
<%= @comment.saywhat %>
<% end %>
<% end %>
If I keep the has many relations in the model, 20 posts on the page render in about 10-15 seconds with say 3 - 4 comments each at average.
If I remove the has many relations, all 20 posts load within 1 - 2 seconds. What I wanted to understand was is this expected to behave this way? I mean is the time taken to parse has many relations so much or I am doing something wrong?
Are others facing similar latencies?
Have you looked at the network traffic? It sounds like you're running into an n+1 issue, round-tripping to the server for each record.
No, there is only one initial request that goes and returns the results. The initial request returns the post along with the 'has many' comments, that's how we have built the service also which is returning the posts along with the comments embedded. In the view we have to run a for each for the comments and I am sure it does not make more requests for those comments. The HER results already has the comments.
Update - Looks like the result is returned pretty fast i.e.
@posts = Post.all
@posts is ready within 1 sec
If it output what's in post, instead of the suggested results, its the HER object something like -
p @posts - #<Her::Model::Relation:0xa42324 @parent=Post, @params={:query=>"{"queryType": "all"}", :from=>"0", :size=>20, :sort=>"creationDate", :order=>"ASC"}, @_fetch=nil>
If I run @posts.each and print each p post.title -
this is when it gets slow and takes like 10 seconds
Does this help narrowing down the issue?