在 Rails 迁移中使用模型关联时出现问题
我正在尝试解决一些问题,向评论表添加一列并执行一些更新。但一整天都出现这个错误:
耙子中止!发生错误, 所有后来的迁移都被取消:
当你没有的时候你有一个nil对象 期待吧!您可能期望 ActiveRecord::Base 的实例。这 评估 nil 时发生错误。[]
迁移代码:
class AddCommenterNameToComments < ActiveRecord::Migration
def self.up
add_column :comments, :commenter_name, :string
Comment.reset_column_information
#to update all comments with commenter name
Comment.all.each do |comment|
unless comment.is_system_message?
comment.update_attribute(:commenter_name, comment.user.name )
end
end
end
def self.down
remove_column :comments, :commenter_name
end
end
请帮忙。
I´m trying to fix some problems adding a column to comments table and performing some updates. But all day having this error:
rake aborted! An error has occurred,
all later migrations canceled:You have a nil object when you didn't
expect it! You might have expected an
instance of ActiveRecord::Base. The
error occurred while evaluating nil.[]
Migration code:
class AddCommenterNameToComments < ActiveRecord::Migration
def self.up
add_column :comments, :commenter_name, :string
Comment.reset_column_information
#to update all comments with commenter name
Comment.all.each do |comment|
unless comment.is_system_message?
comment.update_attribute(:commenter_name, comment.user.name )
end
end
end
def self.down
remove_column :comments, :commenter_name
end
end
Please, help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关联可能不是问题,但要测试是否是问题,您可以通过传入 Comments 表中的
user_id
列来搜索 User 对象。因此,例如:使用 OP 进行编辑 建议的修复
现在也就是说,问题可能是您在 comments 表中的 user_id 不再对应于 Users 表中的 User 对象。您可能还想检查一下,以防关联不是问题所在。
The association might not be the problem, but to test if it is you could search the User object by passing in the
user_id
column from the Comments table. So, for example:Edited with OP Proposed fix
Now that said, the problem could be that you have a user_id in the comments table which no longer corresponds to a User object in the Users table. You might want to check for that as well, in case the association turns out not to be the problem.