我遇到了这个无法解释的 ActiveRecord::Relation, undefined method error 。我不知道为什么,因为我的模型关联定义良好,并且事件表具有用户表的外键。我尝试使用此修复程序但失败了:Rails 3 ActiveRecord::Relation random associations behavior
事件.rb
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'
最佳答案
如果您仔细阅读错误消息,它不会说问题出在与事件的关系上。
它说:
undefined method `events' for
10: <% @users.events.each do |event| %>
当我第一次碰到它时,我也很难理解它
这意味着@users 的查找器正在返回一个 Relation 对象,而不是您期望的用户列表(或名称不正确的对象)。
如果您在任何地方使用查找,您应该将其更改为“where(:id => ...).first”
例如,您的 Controller 中可能有如下内容:
@users = User.find(<conditions go here>)
这应该改为:
@users = User.where(<conditions go here>).all
或者您可以在“where”之后使用生成的关系对象作为额外条件和 sql“配置”
@users = User.where(:admin => true).where('created_at > ?', min_date).order('created_at').limit(10).all
关系对象只有在调用“.first”、“.all”、“.each”或“.inspect”时才会执行查询。
关于ruby-on-rails - rails 3.0.3 - ActiveRecord::Relation,未定义的方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4542348/