Variable/reference question

Hi!

I feel stupid for having to ask this, but I have never run into this
before…

I have this code that should send an email when someone upgrades their
account. I am using this code:

new_plan = Plan.find(params[:customer][:plan_id])
previous_plan = @customer.plan
@customer.change_plan(new_plan)
@customer.save!
ElectronicMailer.deliver_notify_upgrade(@customer.name,
@customer.url, @customer.plan.name, previous_plan.name,
@customer.billing_id, @customer.start_date) # if new_plan.price >
previous_plan.price

The problem is an email never gets send, because new_plan.price is
always equal to previous_plan.price, so it apparently previous_plan
holds a reference to the customer’s plan and when I change that,
previous_plan changes too.

When I change: previous_plan = @customer.plan
to: previous_plan = Plan.find(@customer.plan_id)

it does work, but it feels like I don’t need the extra find…

How would you guys do this?

Thanks,
Mischa.

Yes, previous_plan is a reference to @customer_plan and so changes
with it. Instead of

previous_plan = @customer.plan

This should work with something like

previous_plan = @customer.plan.dup

Which makes previous_plan a copy rather than a reference.

Though not a huge deal, this to me is one of the more annoying and
confusing bits of Ruby. It uses references in many places where I’d
think it would just copy values. And the difference between dup and
clone is poorly documented or mysterious or both.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs