如何在 rails 迁移中向关联(外键)添加默认值



我有一个保险计划,我想添加到客户。 新客户应默认使用具有密钥 1 的省级保险计划。

使用 Rails 5.0,我知道如何将默认值添加到常规列,但是如何将默认值添加到一对一关联? 我是否需要指定对象或仅指定键的值?

在我看来,最好不要在迁移中对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

运行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
未来

数据的默认值应该按照Teja Dandu的建议@Ravi模型中设置

但是,在添加引用时,可以使用这样的迁移,以便使用三步过程设置具有外键的非空引用

  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

最新更新