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 :auction
belongs_to :user
end
在页面上显示拍卖,用户输入金额并点击出价。控制器代码可能如下所示:
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
到目前为止这很有效!但是,我需要确保其他一些事情发生。
@ab.auction.bid_count
需要增加一个。@ab.user.bid_count
需要增加一个@ab.auction.current_winner_id
需要设置为@ab.user_id
也就是说,与User
相关联的Auction
和AuctionBid
也需要更新值,以便AuctionBid#save
返回true。
答案 0 :(得分:11)
Base#save和Base#destroy都包含在transaction中,可确保您在验证或回调中执行的任何操作都会在交易的受保护保护下进行。因此,您可以使用验证来检查事务所依赖的值,或者您可以在回调中引发异常以进行回滚,包括after_ *回调。
class AuctionBid < ActiveRecord::Base
belongs_to :auction, :counter_cache => true
belongs_to :user
validate :auction_bidable?
validate :user_can_bid?
validates_presence_of :auction_id
validates_presence_of :user_id
# the real magic!
after_save :update_auction, :update_user
def auction_bidable?
errors.add_to_base("You cannot bid on this auction!") unless auction.bidable?
end
def user_can_bid?
errors.add_to_base("You cannot bid on this auction!") unless user.can_bid?
end
protected
def update_auction
auction.place_bid(user)
auction.save!
end
def update_user
user.place_bid
user.save!
end
end
FrançoisBeausoleil+1。感谢:foreign_key
建议,但需要在数据库中缓存current_winner_*
列以优化查询。
Alex +1。感谢您让我开始使用Model.transaction { ... }
。虽然这对我来说并不是一个完整的解决方案,但它肯定有助于我指明正确的方向。
答案 1 :(得分:4)
您可能会覆盖AuctionBid.save,如下所示:
def save
AuctionBid.transaction {
auction.bid_count += 1
user.bid_count += 1
auction.current_winner_id = user_id
auction.save!
user.save!
return super
}
end
您可能还需要捕获事务块中引发的异常并返回false。我认为您还需要将belongs_to :auction
添加到AuctionBid
才能引用竞价对象。
答案 2 :(得分:1)
您希望通过将:counter_cache添加到belongs_to associations来启用counter caching。
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 :auction, :counter_cache => true
belongs_to :user, :counter_cache => true
end
请记住通过迁移添加列。要创建竞价出价并设置用户,我建议使用以下代码:
class MyController
def bid
@ab = current_user.auction_bids.build(params[:auction_bid])
if @ab.save
render :json => {:response => 'YAY!'}
else
render :json => {:response => 'FAIL!'}
end
end
end
保存步骤,并确保永远不会忘记分配用户。
最后一项要求是找到当前的赢家。这实际上是拍卖中的has_one关联。您不需要列:
class Auction
# has_one is essentially has_many with an enforced :limit => 1 added
has_one :winning_bid, :class_name => "AuctionBid", :order => "bid_amount DESC"
end