Ruby on Rails-嵌套属性:如何从子模型访问父模型 [英] Ruby on Rails - nested attributes: How do I access the parent model from child model

查看:56
本文介绍了Ruby on Rails-嵌套属性:如何从子模型访问父模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个这样的模型

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不可用.

The above validation so obviously doesn't work because when I'm reading the bill_items from nested attributes inside the bill form, the attributes bill_item.bill_id or bill_item.bill are not available before being saved.

那我该怎么做呢?

推荐答案

这是我最终解决问题的方法;通过在回调中设置父项

This is how I solved it eventually; by setting parent on callback

  has_many :bill_items, :before_add => :set_nest

private
  def set_nest(bill_item)
    bill_item.bill ||= self
  end

这篇关于Ruby on Rails-嵌套属性:如何从子模型访问父模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆