Rails:更新后无法保存对象!

时间:2010-11-21 08:01:26

标签: ruby-on-rails activerecord ruby-on-rails-3

我是rails开发的新手。 我在Post类中放置了一个自定义方法,我想在其中更新该Post类的特定属性/变量。我的方法如下: -

def update_bid_winner (winner_id)
  @bid_winner_id = winner_id
  puts @bid_winner_id
  save
  puts "post saved"
end

但是当我显示Post对象时,bid_winner_id变量仍未更新 我怀疑在更新后对象的保存不成功,因为
put放置上面的方法打印我正在尝试更新的正确值。

从我的rails服务器窗口登录: -

2      <<< Output of the puts placed for debugging
post saved


Started GET "/posts/1/bids/1/offer_bid" for 127.0.0.1 at Sun Nov 21 13:21:59 +0530 2010
Processing by BidsController#offer_bid as HTML
Parameters: {"post_id"=>"1", "id"=>"1"}
User Load (3.1ms)  SELECT "users".* FROM "users" WHERE ("users"."id" = 1) LIMIT 1
Post Load (3.1ms)  SELECT "posts".* FROM "posts" WHERE ("posts"."id" = 1) LIMIT 1
Bid Load (0.5ms)  SELECT "bids".* FROM "bids" WHERE ("bids"."id" = 1) LIMIT 1
Redirected to http://localhost:3000/posts/1
Completed 302 Found in 167ms

我的帖子架构如下: -

create_table "posts", :force => true do |t|
t.integer  "user_id"
t.string   "title"
t.text     "body"
t.integer  "bid_winner_id"
end  

我在这里做错了什么?

2 个答案:

答案 0 :(得分:3)

使用访问器方法而不是实例变量@bid_winner_id

def update_bid_winner (winner_id)
  self.bid_winner_id = winner_id
  puts self.bid_winner_id
  save
  puts "post saved"
end

答案 1 :(得分:1)

您无需自定义方法即可完成此操作。 Rails有一个方便的方法叫update_attribute

@post.update_attribute(:bid_winner_id,winner_id)

哪个会起作用,但即使这不是惯用的Rails。如果帖子与BidWinner模型相关联,并假设您找到(或创建)了一个BidWinner并将其分配给@bid_winner,那么您只需说:

@post.bid_winner = @bid_winner
@post.save

另一件事 - 你不是真的通过GET更新这个,是吗?这通常不是一件好事。