Rails 3 迁移 update_all 与关系/连接
鉴于以下模型,
class User
has_many :conversations
end
class Conversation
belongs_to :user
has_many :messages
end
class Message
belongs_to :conversation
end
我想删除对话模型并将对用户的引用迁移到消息。 通常我会使用类似
add_column :messages, :user_id, :integer
Message.reset_column_information
Message.all.each do |message|
message.user_id = message.conversation.user_id
end
remove_column :messages, :conversation_id
但在生产迁移中在代码更新后运行的内容。因此这会引发错误。
也许我只需要一点提示。
Given Following Models
class User
has_many :conversations
end
class Conversation
belongs_to :user
has_many :messages
end
class Message
belongs_to :conversation
end
I want to remove the Conversation model and migrate the reference to a user to Message.
Normally I would use something like
add_column :messages, :user_id, :integer
Message.reset_column_information
Message.all.each do |message|
message.user_id = message.conversation.user_id
end
remove_column :messages, :conversation_id
But in Production migrations run after the code was updated. Therefore this would throw an error.
Probably I just need a little hint.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
即使您删除了“belongs: to”关系,消息仍应将“conversation_id”作为字段,对吧?
那么如果你这样做了怎么办:
message.user_id = User.find_by_id(message.conversation_id).user_id
Message should still have 'conversation_id' as a field even though you removed the belongs: to relationship right?
So what if you did:
message.user_id = User.find_by_id(message.conversation_id).user_id
一个好的解决方案是在迁移中定义一个临时模型 -> 来源:Rails 指南
A good solution is to define a temporary model inside the migration -> Source: Rails Guides