ruby-on-railsmodelrelationshipeachnested-resources

.each Statement Based on Nested Resources


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| %>


Solution

  • 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)