hp001
hp001

Reputation: 79

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.

Upvotes: 0

Views: 1147

Answers (3)

Ihor
Ihor

Reputation: 297

First of all you should define a has_many relationship between client and workers.

class User < ApplicationRecord
  has_many :workers
end

class Worker < ApplicationRecord
  belongs_to :user
end

More info: Active Record has_many association

Then in the 'show' action you should get workers that are related for particular user. For example:

# GET /clients/1
# GET /clients/1.json
def show
  user = User.find(params[:id]) # find specific user
  @workers = user.workers # get workers related to this user

  # or you can do something like this
  @workers = Worker.where(user_id: params[:id])
end

Upvotes: 0

GoGoCarl
GoGoCarl

Reputation: 2519

To answer your question directly:

def show
  @client  = Client.find params[:id]
  @workers = @client.workers
end

Assuming you are using resourceful routing, the params hash will include the id portion of the URL path, which, here, is /clients/:id. So, you can use that to find the specific client in question, then get the works for that client.

But there's plenty of details on this topic that you'll probably want to read here: http://guides.rubyonrails.org/routing.html#nested-resources

Upvotes: 0

coreyward
coreyward

Reputation: 80041

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!

Upvotes: 3

Related Questions