gpt4 book ai didi

ruby-on-rails - Rails 交易 : save data in multiple models

转载 作者:行者123 更新时间:2023-12-04 00:53:32 25 4
gpt4 key购买 nike

我的模特

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

当前使用情况

页面上显示拍卖,用户输入金额并点击出价。 Controller 代码可能如下所示:
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

  • 也就是说, UserAuctionAuctionBid 相关联还需要更新值以用于 AuctionBid#save返回真。

    最佳答案

    保存和销毁自动包装在一个事务中
    ActiveRecord::Transactions::ClassMethods

    Both Base#save and Base#destroy come wrapped in a transaction that ensures that whatever you do in validations or callbacks will happen under the protected cover of a transaction. So you can use validations to check for values that the transaction depends on or you can raise exceptions in the callbacks to rollback, including after_* callbacks.


    真正的大会!
    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
    荣誉奖
    弗朗索瓦·博索莱 +1。感谢您的 :foreign_key推荐,但 current_winner_*列需要缓存在数据库中以优化查询。
    亚历克斯 +1。感谢您让我开始使用 Model.transaction { ... } .虽然这最终对我来说并不是一个完整的解决方案,但它确实帮助我指明了正确的方向。

    关于ruby-on-rails - Rails 交易 : save data in multiple models,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2468366/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com