1

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!

zenben1126
  • 685
  • 1
  • 7
  • 25

2 Answers2

1

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
infused
  • 24,000
  • 13
  • 68
  • 78
0

One other way of doing it would be to remove the field from Goal model and have a custom field:

class Goal < ActiveRecord::Base
    belongs_to :user
    #....

    def currency
         user.currency
    end
end

So, without any calculations, always:

@goal.currency == @goal.user.currency # => always true
Ruby Racer
  • 5,690
  • 1
  • 26
  • 43