Ruby on rails 使用访问属性有很多关系
我有一个控制器,看起来像这样:Ruby on rails 使用访问属性有很多关系,ruby-on-rails,Ruby On Rails,我有一个控制器,看起来像这样: class EventController < ApplicationController def index ... @events = Event.where(['eventdate < ?', DateTime.now]).order("eventdate") ... end end event.event\u items.event\u comment行引发错误:未定义的方法“event\u comment”,
class EventController < ApplicationController
def index
...
@events = Event.where(['eventdate < ?', DateTime.now]).order("eventdate")
...
end
end
event.event\u items.event\u comment
行引发错误:未定义的方法“event\u comment”,用于[]:ActiveRecord::Relation
为什么我不能作为一种方法访问event\u comment
如果我只使用event.event\u items
该行不会显示错误,而是显示整个event\u items数组,其所有内容都显示在我的视图中
因此,我想也许我可以通过以下方式访问事件\u注释
,作为数组的一部分:
<%= event.event_items.event_comment[i] %> #where i is the index of event_comment in the array
#其中i是数组中事件注释的索引
但这不会在我的显示中返回任何内容
关于如何访问存储在我的
event\u items
db表中的属性event\u comment
有什么建议吗?非常感谢您的帮助 出现该错误的原因是因为event.event\u items
返回ActiveRecord::Relation
,而不是EventComment
的实例。尝试使用:
event.event_items.first.event_comment
事件项是如何定义的?
<%= event.event_items.event_comment[i] %> #where i is the index of event_comment in the array
event.event_items.first.event_comment