A. Singla A. Singla - 4 months ago 7
Ruby Question

Changing Variable Parameters in Different Controller

I have a two models in rails, a purchase and a piece. Whenever a purchase is created, I want to set the status of the piece associated with that purchase to 3. Here is my code right now:

In my purchase controller:

piece = Piece.find(params[:piece_id])
# This works, as when the purchase is created in my view, it passes the piece_id as a hidden field.

Purchase.create(
parameter_1 = blah,
parameter_2 = blah,
piece_id = piece.id
)
#This also works

piece.status = 3


The last line is the line I am having trouble with. The
piece
seems to be an instance variable, and I cannot change the status of actual object it is representing. How can I access this actual object and change its status?

Thanks.

Answer

When you do piece.status = 3, the object in your piece local variable acquires the value, but in order to actually persist the change you have to save the object:

piece.status = 3
piece.save!