如何在Rails迁移中为关联(外键)添加默认值?

3

我有一个覆盖计划,我想为客户添加。新客户应默认使用省级覆盖计划,其关键字为1。

使用Rails 5.0,我知道如何为常规列添加默认值,但是如何为一对一关联添加默认值呢?我需要指定对象还是只需要指定关键字的值?

3个回答

4

我认为,在迁移中不要硬编码foreign_key的值会更好。

你可以像这样做,而不是在迁移中设置默认值:

before_create :set_default_plan

def set_default_plan
  plan = Plan.find_by(name: 'default plan name')
  self.plan = plan if plan.present?
end

2

正如@Ravi Teja Dandu建议的那样,未来数据的默认值应在模型中设置

但是,当您添加引用时,您可以使用此迁移,通过三个步骤让您设置一个具有外键的非空引用

  1. 设置具有外键的引用,但允许为空
  2. 手动为每个项目设置一个值
  3. 更改引用以禁止为空
class AddCategoryToMenuItems < ActiveRecord::Migration[5.2]

   def change
        add_reference :menu_items, :drink_category, foreign_key: true, index: true, null: true

        reversible do |change|
            change.up do
                first_category = DrinkCategory.first
                MenuItem.find_each do |item|
                    item.drink_category = first_category
                    item.save
                end

            end
        end

        change_column_null :menu_items, :drink_category_id, false
    end
end

1

运行rails generate之后

rails g migration AddCoverageToClients coverage:reference

在创建子表coverages中的数据时,将外键的值指定为默认值。
class AddCoverageToClients < ActiveRecord::Migration[5.0]
  def change
    add_reference :clients, :coverage, foreign_key: true, null: false, default: 1
  end 
end

注意:我已经走过这条路,它非常脆弱。正如你所说,你需要在覆盖表中有一个初始行,其id为1。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接