Schema: User
id
name string(255)
Schema: Post
id
user_id
title string(255)
在控制器中,我正在查询与User
有has_many
关系的Post
这是我在控制器中所做的
@users = User.posts.where('title = ?','April Contest').group(:id)
现在在视图文件中我正在通过@users
进行迭代。对于每个user
,我需要获取满足title ='April Contest'的帖子。对于我来说,看起来我必须再次查询。
这就是我的观点:
@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
请帮我在视图文件中避免使用user.posts.where('title = ?','April Contest')
试试这个
首先获得用户包括title ='April Contest'的帖子
@users = User.includes(:posts).where("posts.title = ?",'April Contest').references(:post)
现在在视图中你可以使用@users
进行迭代并从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
这样可以避免在视图中再次运行查询。试试这个,让我知道
尝试使用eager_load
@users = User.eager_load(:posts).where("posts.title = ?",'April Contest')
Eager_load使用LEFT OUTER JOIN在单个查询中加载所有关联。
现在,您无需额外查询即可访问帖子