Search code examples
ruby-on-railsrubymodelmoney-rails

How to have a model field inherit from another model?


I'm using the money-rails gem for currencies. I have two models: a User and a Goals model. The User model has a :currency field, which money-rails uses to set the currency for the user. The Goals model also has a :currency field. As it stands now, when a User creates a new goal, the controller sets the currency for that goal to the same value as that which is stored in the User model.

As follows:

if @goal.save
  @goal.update_attribute(:currency, current_user.currency)
  redirect_to goals_path, notice: "Goal created!"
else
  render '/goals/new'
end

However, if the user then goes back and changes their currency by editing the User model, this only changes the currency for goals that get created thereafter. How do I set it so that when the user changes their currency, it changes the currency used in all models?

Thank you in advance!


Solution

  • One way to do it is to use an after_save callback in the User model to cascade the change to all the user's goals:

    class User < ActiveRecord::Base
      has_many :goals
    
      after_save :cascade_currency_changes
    
      def cascade_currency_changes
        if currency_changed?
          goals.update_all currency: currency
        end
      end
    end