Rails transaction: save data in multiple models.
Posted
by smotchkkiss
on Stack Overflow
See other posts from Stack Overflow
or by smotchkkiss
Published on 2010-03-18T08:35:19Z
Indexed on
2010/03/18
8:41 UTC
Read the original article
Hit count: 378
ruby-on-rails
|activerecord
my models
class Auction
belongs_to :item
belongs_to :user, :foreign_key => :current_winner_id
has_many :auction_bids
end
class User
has_many :auction_bids
end
class AuctionBid
belongs_to :user
end
current usage
An item is displayed on the page, the user enters an amount and clicks bid. Controller code might look something like this:
class MyController
def bid
@ab = AuctionBid.new(params[:auction_bid])
@ab.user = current_user
if @ab.save
render :json => {:response => 'YAY!'}
else
render :json => {:response => 'FAIL!'}
end
end
end
desired functionality
This works great so far! However, I need to ensure a couple other things happen.
@ab.auction.bid_count
needs to be incremented by one.@ab.user.bid_count
needs to be incremented by one@ab.auction.current_winner_id
needs to be set to@ab.user_id
That is, the User
and the Auction
associated with the AuctionBid
need values updated as well in order for the AuctionBid#save
to return true.
© Stack Overflow or respective owner