3
votes

I'm working with a Model called Recover. Prior to creating the model I would like to save the boolean attribute, Combo.occupied = true using the Recover.combo_id attribute as a reference.

It appears my SQL is executing the query properly, but it is not saving this attribute. How can I save Combo.occupied = true?

recover.rb:

before_create :checkin

protected

def checkin x = Combo.find_by_id(combo_id).occupied = true
end

Rails Console:

Started POST "/recovers" for 127.0.0.1 at 2011-01-06 17:07:24 -0800
Processing by RecoversController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"o1Iu3Y9/rVBOZPoDUgVP/tRfQ8GxbdWC40DbPq9YxUE=", "recover"=>{"combo_id"=>"4", "email"=>"[email protected]"}, "commit"=>"Create Recover"} Recover Load (0.2ms) SELECT "recovers"."id" FROM "recovers" WHERE ("recovers"."email" = '[email protected]') LIMIT 1
Recover Load (0.1ms) SELECT "recovers"."id" FROM "recovers" WHERE ("recovers"."combo_id" = 4) LIMIT 1
Combo Load (0.5ms) SELECT "combos".* FROM "combos" WHERE ("combos"."id" = 4) LIMIT 1 AREL (0.5ms) INSERT INTO "recovers" ("locker_number", "email", "requests", "created_at", "updated_at", "combo_id") VALUES (NULL, '[email protected]', NULL, '2011-01-07 01:07:24.287072', '2011-01-07 01:07:24.287072', 4) Redirected to http://localhost:3000/recovers/14 Completed 302 Found in 119ms

RecoversController#create

def create @recover = Recover.new(params[:recover])

respond_to do |format|
  if @recover.save
    format.html { redirect_to(@recover, :notice =>

'Recover was successfully created.') } format.xml { render :xml => @recover, :status => :created,

:location => @recover }

  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @recover.errors, :status =>

:unprocessable_entity } end

end  

end

1
it's seems no object is created in your RecoversController#create. Could you post the content of this method?apneadiving

1 Answers

5
votes

You need to call save for the new value to be written to the database:

def checkin
  combo = Combo.find_by_id(combo_id)
  combo.occupied = true
  combo.save!
end

This is easier if you use update_attribute. Also, if you have a belongs_to relationship, you can dispense with the find:

belongs_to :combo

def checkin
  if combo # true unless combo_id is nil
    combo.update_attribute(:occupied,true)
  end
end

Note that update_attribute bypasses validation. If you need to validate, use update_attributes(:occupied=>true) instead.