我有这个无法解释的ActiveRecord :: Relation,未定义的方法错误。我不知道为什么,因为我的模型关联定义很好,并且事件表具有用户表的外键。我尝试使用此修复但失败了:Rails 3 ActiveRecord::Relation random associations behavior
class Event < ActiveRecord::Base
belongs_to :user
attr_accessible :event_name, :Starts_at, :finish, :tracks
end
class User < ActiveRecord::Base
has_many :events, :dependent => :destroy
attr_accessible :name, :event_attributes
accepts_nested_attributes_for :events, :allow_destroy => true
end
ActiveRecord::Schema.define(:version => 20101201180355) do
create_table "events", :force => true do |t|
t.string "event_name"
t.string "tracks"
t.datetime "starts_at"
t.datetime "finish"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "user_id"
end
end
NoMethodError in Users#index
undefined method `events' for #<ActiveRecord::Relation:0x4177518>
Extracted source (around line #10):
7: <th><%= sortable "Tracks" %></th>
8: </tr>
10: <% @users.events.each do |event| %>
11: <% debugger %>
12: <tr>
13: <td><%= event.starts_at %></td>
Trace of template inclusion: app/views/users/index.html.erb
Rails.root: C:/rails_project1/events_manager
Application Trace | Framework Trace | Full Trace
app/views/users/_event_user.html.erb:10:in `_app_views_users__event_user_html_erb__412443848_34308540_1390678'
app/views/users/index.html.erb:7:in `_app_views_users_index_html_erb___603337143_34316016_0'
答案 0 :(得分:8)
如果您仔细阅读错误消息,则不会说问题是与事件的关系。 它说:
的未定义方法`events'
10:&lt;%@ users.events.each do | event | %GT;
当我第一次碰到它时,我也很难理解这一点
这意味着@users的finder返回一个Relation对象而不是你期望的用户列表(或者没有命名的对象)。
如果您在任何地方使用查找,则应将其更改为“where(:id =&gt; ...)。first”
例如,你的控制器中可能有这样的东西:
@users = User.find(<conditions go here>)
这应该改为:
@users = User.where(<conditions go here>).all
或者您可以在“where”之后使用结果关系对象获取额外条件和sql“configuration”
@users = User.where(:admin => true).where('created_at > ?', min_date).order('created_at').limit(10).all
只有在调用“.first”“。all”“。double”或“.inspect”时,关系对象才会执行查询。
答案 1 :(得分:5)
一个 user
有很多events
。在您的代码中,您似乎正在尝试访问events
上的@users
,这可能是多个用户。
你可能想做类似的事情:
@users.each do |user|
user.events.each do |event|
...
end
end
或:
@user.map(&:events).flatten.each do |event|
...
end
此外,您无需在数据库中列的任何属性上指定attr_accessible
。