开发者

How can I update another Model using a Callback?

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"=>"jz@marin.edu"}, "commit"=>"Create Recover"} Recover Load (0.2ms) SELECT "recovers"."id" FROM "recovers" WHERE ("recovers"."email" = 'justin.zollars@marin.edu') 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, 'justin.zollars@marin.edu', 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 cre开发者_JAVA百科ated.') } 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜