Pregunta

I have an events model that has many posts, and I'm trying to display the relevant the events and posts in an outline format, like so:

Event 1
  Post 1
  Post 2
Event 2
  Post 3
  Post 4
...

I have the following currently, and for some reason, the controller can't find the "postlist" method (acting on the @eventlist instance) in my Events model.

class Event < ActiveRecord::Base
  belongs_to :group
  has_many :posts

  def postlist
    Post.from_event_posts(self)
  end

end


class Post < ActiveRecord::Base
  belongs_to :event
  belongs_to :user

  def self.from_event_posts(event)
    where(event_id: event.id)
  end

end


class GroupsController < ApplicationController
  def show
    @eventlist = @group.eventlist #returns hash of events for a group - confirmed working

    #Get list of posts for each event
    @postlist = @eventlist.postlist
  end
end



<%= @eventlist.each do |e| %>
<ul>
  <li><%= e.title %></li>
  <%= e.postlist.each do |p| %>
  <ul>
    <li><%= p.comment %> | <%=p.user_id%> </li>
  </ul>
  <%end%>
</ul>
<%end%>

I get the following error: undefined method `postlist' for #

¿Fue útil?

Solución

You get this error because you are calling the method postlist not on one event, but on an array of events. By the way, the general convention in Rails is to call those variables @events and @posts (Just a tip, getting used to it can be convenient later).

Can you show us your group class ?

I would write something like that :

def show
  @events = @group.events.includes(:posts)
end

The includes method will join the posts table to the SQL query you are performing, loading the posts before rendering the view. Your view then look like :

<%= @events.each do |e| %>
  <ul>
    <li><%= e.title %></li>
    <%= e.posts.each do |p| %>
      <ul>
        <li><%= p.comment %> | <%=p.user_id%> </li>
      </ul>
    <%end%>
  </ul>
<%end%>

And I believe you can remove the postlist and the eventlist method. Those kind of functions already exist.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top