Rails 迁移:如何在迁移中合成刚刚创建的列的方法?
我有一个需要新列的表。新引入的列需要一些值,可以从行中的其他字段计算得到。默认没有帮助。
因此,我创建了两个迁移(可能是一个),它将:
- 添加一列(例如:new_column)
- 使用 attr_accessor 更新列
如果我逐一运行这些迁移,它运行时不会出现问题。
但是,当我使用单个迁移请求来运行两次迁移时,看起来 attr_accessor 在迁移 1 后并未合成,因此步骤 2 失败。
目前,我多次调用 rake (每次都在迁移后停止,如上面的步骤 1 所示) 以避免这种情况。
我想我可以在开始使用 attr_accessor 之前合成它,但不知道这种情况下的最佳实践是什么。
解决这个问题的最佳方法是什么?
I have a table which need new column. The newly introduced column need some value, which can be calculated from other fields in the row. Default does not help.
So, I created two migrations (possibly one) which will:
- Add a column (say: new_column)
- Update the column using attr_accessor
If I ran these migrations one by one, it run without problem.
But when I ran both migrations with a single migration request to rake, it looks like the attr_accessor is not synthesized after migration 1, so step 2 fails.
Currently, I call rake several times (each time, stop at after migration like step 1 above)
to avoid this.
I think I can synthesize attr_accessor before start using it, but don't know what is the best practice in this situation.
What is the best way to solve this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在迁移中的类上调用
reset_column_information
,这将重新加载该类中的列。理想情况下,您应该这样做:
永远不要对数据库中的任何真实列使用
attr_accessor
。这会覆盖列的默认 setter 和 getter 方法,并且意味着尝试为此列设置任何值都将不起作用。这是因为您现在使用的是虚拟属性,而不是真实属性。You should call
reset_column_information
on the class inside the migration which will reload the columns in that class.You would ideally do something like this:
Do not use an
attr_accessor
ever for any real column in your database. This overrides the default setter and getter methods for your column and will mean that attempting to set any value to this column won't work. This is because you're now using a virtual attribute, rather than a real one.