Question

Chefs have one Location and Location belongs to Chef.

In the Locations controller, how do I call chefs. Below is what I have so far.

class LocationsController < ApplicationController
  def index
    @chef = Location.find_by_chef_id #This is what I am not getting.  Should it be,
    @chef = Location.find(params[:chef_id])??
    @locations = Location.all
  end
end

I am wanting to call it in my view with something like <%= chef.name %>

Could this be correct?

@location= Location.find(params[:id])
@chef = Chef.find(@location.chef_id)

@chef.each do |chef|
    <%= chef.name %>
end

This brings up this error "Couldn't find Location without an ID"

Was it helpful?

Solution

You can call any model from your LocationsController:

class LocationsController < ApplicationController
  def index
    @chefs = Chef.all
    @chef = Chef.find(params[:id])
    @locations = Location.all
    @location = Location.find(params[:id])
  end
end

If you want to call a chef's name in the view:

@location.chefs.each do |chef|
  <%= chef.name %>
end

It all depends what type of content you're trying to render, but it's best to call models directly in the controller unless certain associations are required.

@location.chefs.each do |chef|
  if !chef.name.blank?
    <%= chef.name %>
  end
end

OTHER TIPS

If each Location belongs_to a Chef, then:

@locations = Location.includes(:chef).all

Then you can iterate over these:

@locations.each do |location|
   location.chef
end

Or if you want all the chefs:

@chefs = @locations.collect(&:chef).uniq

There's probably a better way to fetch this, but it's not clear what you're looking for.

You can search for Location by id, and then just get its chef.

def index
   @location = Location.find(params[:id])
end

then in view:

@location.chef.each do |chef|
   <%= chef.name %>
end

and if chef can be nil use #try method:

@location.chef.try(:each) do |chef|
   <%= chef.name %>
end

But the Location model shell include belongs_to declaration:

class Location < ActiveRecord::Base
   belongs_to :chef
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top