Reputation: 2719
Schema: User
id
name string(255)
Schema: Post
id
user_id
title string(255)
In controller I am querying User
which has has_many
relation with Post
This is what I do in the controller
@users = User.posts.where('title = ?','April Contest').group(:id)
Now in view file I am iterating through @users
. For every user
I need to fetch posts that satisfy title='April Contest'. For me to make this happen, it looks like I have to query again.
This is what I do in view:
@users.each do |user|
A LOT OF HTML THAT DISPLAYS DATA OF USER
user.posts.where('title = ?','April Contest').each do |post|
SOME HTML THAT DISPLAYS DATA OF POST
end
end
Please help me avoid this user.posts.where('title = ?','April Contest')
in the view file
Upvotes: 0
Views: 72
Reputation: 159
Try using eager_load
@users = User.eager_load(:posts).where("posts.title = ?",'April Contest')
Eager_load loads all association in a single query using LEFT OUTER JOIN.
Now you will be able to access posts without an extra query
Upvotes: 1
Reputation: 665
Try this
First get Users including the posts where title = 'April Contest'
@users = User.includes(:posts).where("posts.title = ?",'April Contest').references(:post)
Now in view you can iterate using @users
and get the posts from user.posts
@users.each do |user|
A LOT OF HTML THAT DISPLAYS DATA OF USER
user.posts.each do |post|
SOME HTML THAT DISPLAYS DATA OF POST
end
end
This avoid running the query again in view. Try this and let me know
Upvotes: 1