20

我有几个这样的模型

class Bill < ActiveRecord::Base
  has_many :bill_items
  belongs_to :store

  accepts_nested_attributes_for :bill_items
end

class BillItem <ActiveRecord::Base
  belongs_to :product
  belongs_to :bill

  validate :has_enough_stock

  def has_enough_stock
    stock_available = Inventory.product_is(self.product).store_is(self.bill.store).one.quantity
    errors.add(:quantity, "only #{stock_available} is available") if stock_available < self.quantity
  end
end

上面的验证显然不起作用,因为当我从账单表单内的嵌套属性中读取 bill_items 时,属性 bill_item.bill_id 或 bill_item.bill 在保存之前不可用。

那么我该如何去做这样的事情呢?

4

5 回答 5

18

这就是我最终解决它的方法;通过在回调上设置父级

  has_many :bill_items, :before_add => :set_nest

private
  def set_nest(bill_item)
    bill_item.bill ||= self
  end
于 2011-02-19T06:39:28.270 回答
9

在 Rails 4(未在早期版本上测试)中,您可以通过将inverse_of选项设置为has_many或来访问父模型has_one

class Bill < ActiveRecord::Base
  has_many :bill_items, inverse_of: :bill
  belongs_to :store

  accepts_nested_attributes_for :bill_items
end

文档:双向关联

于 2015-04-22T21:47:36.067 回答
1

bill_item.bill 应该可用,您可以尝试提高 self.bill.inspect 以查看它是否存在,但我认为问题出在其他地方。

于 2010-04-25T15:15:08.627 回答
1

我通过在回调中设置父级来“修复”它:

class Bill < ActiveRecord::Base
  has_many :bill_items, :dependent => :destroy, :before_add => :set_nest
  belongs_to :store

  accepts_nested_attributes_for :bill_items

  def set_nest(item)
    item.bill ||= self
  end
end

class BillItem <ActiveRecord::Base
  belongs_to :product
  belongs_to :bill

  validate :has_enough_stock

  def has_enough_stock
        stock_available = Inventory.product_is(self.product).store_is(self.bill.store).one.quantity
    errors.add(:quantity, "only #{stock_available} is available") if stock_available < self.quantity
  end
end

set_nest 方法成功了。希望它是标准的accepts_nested_attributes_for。

于 2011-01-28T08:54:35.370 回答
0

是的,这种问题可能很烦人。您可以尝试向您的 Bill Item 模型添加一个虚拟属性,如下所示:

class BillItem <ActiveRecord::Base
  belongs_to :product
  belongs_to :bill

  attr_accessible :store_id

  validate :has_enough_stock

  def has_enough_stock
   stock_available = Inventory.product_is(self.product).store_is(load_bill_store).one.quantity
   errors.add(:quantity, "only #{stock_available} is available") if stock_available < self.quantity
  end

  private

  def load_bill_store
    Store.find_by_id(self.store_id)
  end
end

然后在您的视图中,您可以添加一个隐藏字段,如下所示:

<%= bill_item.hidden_field :store_id, :value => store_id %>

这还没有经过测试,但它可能会起作用。您可能不希望在 html 中包含 store_id,但这可能不是问题。让我知道这是否有帮助。

于 2010-04-10T17:12:12.453 回答