.each Statement Based on Nested Resources

39 Views Asked by At

I am trying to write an .each statement based on the characteristic of a nested resource. The relationships between tables in my app are defined as below:

User has_many Posts
Post belongs_to User
Post belongs_to Category
Category has_many Posts

From a page for a given category I would like to index all Users who have a post in that category. What is the best way to accomplish this?

I have been experimenting with various forms of the following statement but have not been successful.

<% User.where(user.post.category == @category).each do |category| %>

3

There are 3 best solutions below

0
Ravi Teja Gadi On BEST ANSWER

In controller:

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

In view

<% @users.each do |user| %>
  <Your html code>
<% end %>

Always keep your business logic out of views. It would be suggested making that query as a scope in the model.

In user.rb

scope :post_users, -> (category_id)  {joins(:post).where(posts: {category_id: category_id})}

In controller

@post_users = User.post_users(@category.id)
1
widjajayd On

you can search users with query below and then list it

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

note: you can put line 1 above in your controller

0
code_aks On

Better approach is to set the @users in controller method or make any helper method to get the result in the view

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

And then in view

#your_view.html.erb

<% @users.each do |user| %>
<% end %>