Reputation: 27
I have a controller which looks something like this:
class EventController < ApplicationController
def index
...
@events = Event.where(['eventdate < ?', DateTime.now]).order("eventdate")
...
end
end
And my model defines the following relationship:
class Event < ActiveRecord::Base
...
has_many :match_items, dependent: :destroy
...
end
I am now trying to access the event_items linked to the events defined in the the instance variable @event
in my view as follows:
<h2>Your Events</h2>
<% @events.each do |event| %>
</br><span>
<%= event.eventdate.to_formatted_s(:rfc822) %>
<%= event.event_items.event_comment %>
</span>
<% end %>
the event.event_items.event_comment
line throws an error: undefined method 'event_comment' for []:ActiveRecord::Relation
Why can't I not access event_comment
as a method?
If I just use event.event_items
the line doesn't display an error and shows the whole event_items array with all it's content displayed in my view.
So i thought maybe I can just access the event_comment
as part of the array through using:
<%= event.event_items.event_comment[i] %> #where i is the index of event_comment in the array
But this then doesn't return anything in my display.
Any suggestions on how I can access the attribute event_comment
stored in my event_items
db table? Any help is very much appreciated!
Upvotes: 0
Views: 77
Reputation: 38645
The reason you are getting that error is because event.event_items
returns a ActiveRecord::Relation
and not an instance of EventComment
. Try using:
event.event_items.first.event_comment
Upvotes: 1