Ruby on rails 。每个语句都基于嵌套资源

Ruby on rails 。每个语句都基于嵌套资源,ruby-on-rails,model,relationship,each,nested-resources,Ruby On Rails,Model,Relationship,Each,Nested Resources,我试图根据嵌套资源的特性编写一个.each语句。我的应用程序中的表之间的关系定义如下: User has_many Posts Post belongs_to User Post belongs_to Category Category has_many Posts 从一个给定类别的页面,我想索引所有在该类别中有帖子的用户。实现这一目标的最佳方式是什么 我一直在尝试以下各种形式的陈述,但都没有成功 您可以使用下面的查询搜索用户,然后将其列出 <% @users = User.joins(

我试图根据嵌套资源的特性编写一个.each语句。我的应用程序中的表之间的关系定义如下:

User has_many Posts
Post belongs_to User
Post belongs_to Category
Category has_many Posts
从一个给定类别的页面,我想索引所有在该类别中有帖子的用户。实现这一目标的最佳方式是什么

我一直在尝试以下各种形式的陈述,但都没有成功


您可以使用下面的查询搜索用户,然后将其列出

<% @users = User.joins(:posts).where('posts.category_id = ?',@category.id) %>
<% @users.each do |user| %>


注意:您可以将上面的第1行放在控制器中更好的方法是在控制器方法中设置
@users
,或使任何助手方法在视图中获得结果

def your_method ## or any other method
  .....
  .....
  @users = User.joins(:posts).where('posts.category_id = ?',@category.id)
end
然后在视野中

#your_view.html.erb

<% @users.each do |user| %>
<% end %>
#your_view.html.erb
在控制器中:

@users = User.joins(:post).where(posts: {category_id: @category.id})
鉴于

<% @users.each do |user| %>
  <Your html code>
<% end %>
内部控制器

@post_users = User.post_users(@category.id)

在控制器操作中定义@users比在视图中定义要好。我们应该尽可能多地避开逻辑观点。
@post_users = User.post_users(@category.id)