我有一个覆盖计划,我想为客户添加。新客户应默认使用省级覆盖计划,其关键字为1。
使用Rails 5.0,我知道如何为常规列添加默认值,但是如何为一对一关联添加默认值呢?我需要指定对象还是只需要指定关键字的值?
我有一个覆盖计划,我想为客户添加。新客户应默认使用省级覆盖计划,其关键字为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
正如@Ravi Teja Dandu建议的那样,未来数据的默认值应在模型中设置
但是,当您添加引用时,您可以使用此迁移,通过三个步骤让您设置一个具有外键的非空引用
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
运行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