Rails transaction: save data in multiple models.
- by smotchkkiss
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.