Ruby on rails RubyonRails-嵌套属性:如何从子模型访问父模型
我有几个这样的模特Ruby on rails RubyonRails-嵌套属性:如何从子模型访问父模型,ruby-on-rails,nested-attributes,Ruby On Rails,Nested Attributes,我有几个这样的模特 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
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
classbill 是的,这种问题很烦人。您可以尝试向账单项目模型添加虚拟属性,如下所示:
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 %>
类BillItem
这还没有经过测试,但可能会奏效。您可能不希望在html中使用store_id,但这可能不是一个问题。让我知道这是否有帮助 bill\u item.bill应该可用,您可以尝试执行raise self.bill.inspect以查看它是否存在,但我认为问题出在其他地方。我通过在回调中设置parent来“修复”它:
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
classbill:销毁,:在添加=>:设置\u嵌套之前
属于:商店
接受下列项目的\u嵌套\u属性\u
def集合_嵌套(项目)
item.bill | |=self
结束
结束
类BillItem这就是我最终解决它的方法;通过在回调上设置父级
has_many :bill_items, :before_add => :set_nest
private
def set_nest(bill_item)
bill_item.bill ||= self
end
在Rails 4(未在早期版本上进行测试)中,您可以通过在has\u many
或has\u one
上设置inverse\u of
选项来访问父模型:
class Bill < ActiveRecord::Base
has_many :bill_items, inverse_of: :bill
belongs_to :store
accepts_nested_attributes_for :bill_items
end
classbill
文档:即使它不可用,OP也可以添加一个before\u验证回调来设置它。BillItems不需要知道自己的ID或父Bill的ID才能进行验证。我通过向关联添加一个回调来解决这个问题,:before\u add=>:set\u nestYeah!最近它一直困扰着我。我希望它是自动的,如果回调函数是针对关联代理(比如关联扩展)而不是关联所有者运行的,那么可以编写一个更通用的版本