Search code examples
ruby-on-railsrubymodel-associations

Rails: List all of Parent's children in Parent's Show


In my rails app I can create a client and a worker for that client. Currently, I'm able to list all the workers that have been created. However, this list includes the workers for other clients too.

How do I only list all the workers for a specific client in the client show page?

I have a feeling it has to do with my client#show method.

  class ClientsController < ApplicationController
  before_action :set_client, only: [:show, :edit, :update, :destroy]

  # GET /clients
  # GET /clients.json
  def index
    @clients = Client.all
  end

  # GET /clients/1
  # GET /clients/1.json
  def show
    @workers = Worker.all
  end


  # views/clients/show.html.erb
  <ul>
   <% @workers.each do |worker| %>
    <li><%= worker.first_name %> <%= worker.client.business_name %></li>
   <% end %>
  </ul>

Thanks in advance.


Solution

  • In your ClientsController, your show action should be showing a Client, but your code is fetching from Worker. You want something more like this:

    def show
      @client = Client.includes(:workers).find(params[:id])
    end
    
    # app/views/clients/show.html.erb
    <% @client.workers.each do |worker| %>
      <%= worker.name %>
    <% end %>
    

    Note: it looks like you also have a set_client method that is retriving the current Client and setting the @client instance variable. This is something of an antipattern; in many cases you retrieve data you don't need and make your actions harder to understand at a glance. A small amount of non-logic duplication is better than confusing abstractions!