将一些硬编码文件更改为活动记录模型的好方法是什么?
现在,我的产品模型有一个类别字符串列,表单有一个选择,可以从产品模型中的数组中获取其值。目前只有三种可能的类别:wood_stoves、arborist_gear 和链锯。我有一个控制器,其中每个控制器都有一个操作,列出了各自类别的产品。
我将类别切换到数据库表,并使用 has_many 和 Belongs_to 关系在其中嵌套产品,这是我的问题。以下是一个坏主意吗?
- 为每个 wood_stoves、arborist_gear 和链锯创建一条记录。
- 创建一个迁移,将产品/类别列中每个值转换为新创建的类别记录中相应的记录 ID 整数。
- 在迁移中添加一个步骤,将category.string 列更改为category.integer 列。
- 在迁移中添加必要的向下步骤以恢复所有这些。
简而言之,我应该在迁移中完成所有这些操作,以便它是可逆的,还是应该放弃可逆性并手动对数据库进行更改,以避免看起来有些荒谬的迁移,该迁移只能反转与原始类别相对应的产品?换句话说,迁移将无法撤消属于新创建类别的产品。
Right now my products model has a string column of category, with the form having a select which gets its values from an array in the product model. Right now there are only three possible categories: wood_stoves, arborist_gear, and chainsaws. I have a controller with an action for each of those that lists the products for their respective category.
I'm switching the categories to a database table and nesting products in it with has_many and belongs_to relationships, and here's my question. Is the following a bad idea?
- Create a record for each of wood_stoves, arborist_gear, and chainsaws.
- Create a migration that converts the value of each of those in the products/category column into the corresponding record id integer from the newly created categories records.
- Add to the migration a step that changes the category.string column to a category.integer column.
- Add to the migration the necessary down steps to revert all that.
In short, should I do all this in a migration so it's reversible, or should I abandon reversibility and manually make the changes to the database to avoid a somewhat ridiculous looking migration that will only be able to reverse products that correspond to the original categories? In other words, the migration won't be able to reverse products that belong to newly created categories.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来不错。我唯一要做的不同就是坚持 Rails 约定,即外键列名称以“_id”结尾。这样生活就更容易了。在您的情况下,从产品模型中删除
category
列,并添加category_id
列。Sounds good. The only thing that I would do different is stick with the Rails convention of having a foreign key column name end with "_id". Life is just easier that way. In your case remove the
category
column from your products model and add acategory_id
column.