How do I set a default value based on an associated model in Rails?

Viewed 86

I have a model called userWorkshop it references both a User and a Workshop.

Workshops have a price column.

userWorkshops have an override_price column.

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.

I want to set this value in my ActiveRecord migration. 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?

1 Answers

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.

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.

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
Related