[英]How do I set a default value based on an associated model in Rails?
I have a model called userWorkshop
it references both a User
and a Workshop
.我有一个名为 userWorkshop 的userWorkshop
它引用了User
和Workshop
。
Workshops
have a price column. Workshops
有一个价格栏。
userWorkshops
have an override_price column. userWorkshops
有一个override_price列。
I would like its default value of the override_price column of the UserWorkShop
to be based on the price column of the Workshop
it is associated with.我希望UserWorkShop
的override_price列的默认值基于与之关联的Workshop
的price列。
I want to set this value in my ActiveRecord migration.我想在我的 ActiveRecord 迁移中设置这个值。 I imagine it might look something like this:我想它可能看起来像这样:
def change
add_column :userWorkshops, :override_price, :float, default: "self.workshop.price"
end
Any idea on the correct way to do this?关于正确方法的任何想法?
I'm not sure if there is a way to do all of this in one migration.我不确定是否有办法在一次迁移中完成所有这些工作。 I would take advantage of the before_initialize callback.我会利用 before_initialize 回调。
class UserWorkshop < ApplicationRecord
has_many :users
belongs_to :workshop
before_initialize :initial_values, unless: persisted?
def initial_values
self.override_price = workshop.price
end
end
The benefit of this is that you can easily change your override_price to be something like this self.override_price = workshop.price/2
to give them a 50% discount or anything else of that sort.这样做的好处是您可以轻松地将您的 override_price 更改为类似self.override_price = workshop.price/2
的内容,以给予他们 50% 的折扣或其他类似的东西。
And then in a migration, something to take care of the old data.然后在迁移中,需要处理旧数据。
def change
UserWorkshop.find_each do |uw|
uw.override_price = uw.workshop.price
uw.save
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.