Question

My Chefs Model is linked to my Meals Model through chef_id. I am displaying information about the chef, and would also like to show information about his meals. I have not been able to figure out the correct way to call it in the controller. Any ideas?

chef controller:

def index
    @chefs=Chef.paginate(page: params[:page])
    @meals = ????? Cant figure out how to call this
end 

Index.html.erb

<div class = 'chef'>
    <div class = 'row'> 


               <% @chefs.each do |chef| %>
                <%= render chef %>

            <% end %>


    </div>
</div>
<%= will_paginate %>

_chef partial

<div class = 'span4'>
    <div class = 'chef-box'>
        <h2><center><%= link_to chef.name, chef %></center></h2>
        <h2><center>"<%= chef.description %>"</center></h2>
        <h2><center><%= THIS IS WHERE I WANT TO DISPLAY INFORMATION ON MEALS %></center></h2>
    </div>
</div>
Was it helpful?

Solution

If you just want to access the @meals, than you can get it just by for an instance of @chef:

@meals = @chef.meals 

given that you have defined the association in the Chef class like following:

class Chef < ActiveRecord::Base
  has_many :meals

  #rest of the code
end

Have a look at Active Record Associations here.

So, Here I am just giving an example of how to use it in views, you may have to correct it: in _chef partial

<div class = 'span4'>
    <div class = 'chef-box'>
        <h2><center><%= link_to chef.name, chef %></center></h2>
        <h2><center>"<%= chef.description %>"</center></h2>
              <% chef.meals.each do |meal| %>
                 <h2><center><%= meal.information %></center></h2>
            <% end %>
    </div>
</div>

You will need to call correct attribute of meal in above sample code.

OTHER TIPS

As previously mentioned – first and foremost make sure the relation is set up in your chef model:

class Chef < ActiveRecord::Base
  has_many :meals
end

Then you can call any Chef.meals, whether that's in your controller as:

def index
  @chef = Chef.paginate(page: params[:page])
  @meals = @chef.meals
end

Or just in your view:

<div class = 'span4'>
    <div class = 'chef-box'>
        <h2><center><%= link_to chef.name, chef %></center></h2>
        <h2><center>"<%= chef.description %>"</center></h2>
        <h2>Has <%= pluralize(chef.meals.size, 'meal') %></h2>
        <% chef.meals.each do |meal| %>
          <% meal.name %>
        <% end %>
    </div>
</div>

Of note – since Chef is a model name, you should be able to render your _chef.html.erb more cleanly with simply:

<div class = 'chef'>
    <div class = 'row'> 
      <%= render @chef %>
    </div>
</div>
<%= will_paginate %>

Note that @chef is singular to match your controller, you could also pass it a collection <%= render @chefs %> if that's what's set up in your controller, and it will do render each chef separately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top