Reputation: 5145
I'm a newbie to rails development. I have a custom method placed in my Post class, in which I want to update a particular attribute/variable of that Post class. My method goes as below:-
def update_bid_winner (winner_id)
@bid_winner_id = winner_id
puts @bid_winner_id
save
puts "post saved"
end
But when I display the Post object , the bid_winner_id variable is still not updated.
I doubt that the object's save is not successful after the updation, because
the puts placed the above method prints the correct value with which I'm trying to update.
Logs from my rails server window:-
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
My post schema as follows:-
create_table "posts", :force => true do |t|
t.integer "user_id"
t.string "title"
t.text "body"
t.integer "bid_winner_id"
end
What Am i doing wrong here ???
Upvotes: 1
Views: 661
Reputation: 47548
You don't need a custom method to accomplish this. Rails has a handy method called update_attribute
:
@post.update_attribute(:bid_winner_id,winner_id)
which will work, but even that is not idiomatic Rails. If a Post is associated to the BidWinner model, and assuming you found (or created) a BidWinner and assigned it to @bid_winner), then you simply say:
@post.bid_winner = @bid_winner
@post.save
One other thing -- you aren't really updating this via a GET, are you? That would generally not be a good thing.
Upvotes: 1
Reputation: 17577
Use accessor method instead of instance variable @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
Upvotes: 3