【问题标题】:Rails callback after_save not setting attributeRails 回调 after_save 未设置属性
【发布时间】:2012-08-10 10:45:19
【问题描述】:

我正在处理 after_save 回调的问题。我确信有一个简单的解决方案,但我无法弄清楚。

我有 3 个模型:用户、产品、投标。 Product 表包含一个布尔字段“available”,默认设置为true。如果用户出价,则可用字段应设置为 false。 我认为这应该与出价模型的回调一起使用。 我可以通过键入以下内容访问和设置控制台中的可用字段: b = 出价.最后 b.product.available = false => 假的 但是我不能通过控制器改变它,所以我认为它不会执行回调。我究竟做错了什么? 谢谢大家的帮助!

product.rb

class Product < ActiveRecord::Base

has_one :bid
belongs_to :user
end

bid.rb

class Bid < ActiveRecord::Base
attr_accessible :product_id, :user_id, :product
belongs_to :product
belongs_to :user
after_save :set_product_status

def set_product_status
self.product.available = false
end
end

bids_controller.rb

...
def create
@user = current_user
product = Product.find(params[:product_id])
@bid = @user.bids.build(product: product)

respond_to do |format|
if @bid.save
...

【问题讨论】:

    标签: activerecord callback ruby-on-rails-3.2


    【解决方案1】:

    既然出价属于产品,你也应该保存产品。

    def set_product_status
      self.product.available = false
      self.product.save
    end
    

    【讨论】:

    • 谢谢!那行得通!我发现它也适用于:product.available = false product.save 所以它似乎也不需要“自我”参考。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 2011-11-28
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多