crcerror
crcerror

Reputation: 119

Rails - get objects belong to other objects

appreciate if you help me. I'm using rails 4.2.

I have 2 models - Epoch and Event. Every epoch has many events.

I want to make list with events for every epoch:

<% @epoches.each do |epoch| %>
    <div><%= epoch.main_title %> : </div>
    <% @events.each do |event| %>
        <div><%= event.title %></div>
    <% end %>
<% end %>

my epoches_controller.rb looks like:

def epochline
    @epoches = Epoch.all
    @events = Epoch.find(params[:id]).event.all
end

When i call in console "Epoch.find(1).events.all" it works amazing, but web-server return error - "Couldn't find Epoch with 'id'=". What am i doing wrong? How can I edit my controller to solve this problem?

Upvotes: 0

Views: 74

Answers (1)

user7252292
user7252292

Reputation:

Remove the @events = Epoch.find(params[:id]).event.all line in the controller and the view should be this.

<% @epoches.each do |epoch| %>
    <div><%= epoch.main_title %> : </div>
    <% epoch.events.each do |event| %>
        <div><%= event.title %></div>
    <% end %>
<% end %>

Edit: You can eager load events by doing @epoches = Epoch.includes(:events) in your controller. That will cache both epochs and events and also will prevent doing sql queries in your view

Upvotes: 3

Related Questions