【发布时间】:2014-07-20 15:30:36
【问题描述】:
我的 rails 4 应用有 3 个模型:
- 商店(has_many :products)
- 产品(has_many :product_fields 和 belongs_to :store 和 accept_nested_attributes_for product_fields
- Product_fields(有一个 belongs_to :product)
产品只有 store_id 和 id 字段。 Product_fields 有 string_content 和 text_content。基本上,现在我的商店模型看起来像:
class Store < ActiveRecord::Base
has_many :products
accepts_nested_attributes_for :products, :allow_destroy => true, :reject_if => :product_empty
private
def product_empty(a)
a[:product_fields_attributes][:text_content].blank?
end
end
如果我在未填写 text_content 的情况下创建新商店,模型会正确拒绝它(并且不会创建产品或产品字段)。不幸的是,问题是如果我真的做 填写 text_content,那么它仍然不会创建它。
我的 rails 控制台看起来像:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"nFUg4ynXYyg99rPPPoa3uO/iHP4LT1XlOz3Vm3Zm4Z0=", "store"=>{"name"=>"Test", "products_attributes"=>{"0"=>{"type_of"=>"Book", "product_fields_attributes"=>{"0"=>{"text_content"=>"test1"}}}}}, "commit"=>"Create Store"}
我的问题是:如何让 reject_if 方法在嵌套模型上工作?所以,要明确一点,我不想验证嵌套模型,我只想不保存关联的 product_field text_content 为空的产品?。
【问题讨论】:
-
如果您的意思是您的属性中的 product_fields_attributes,那么是的,这是可能的。如果要使用 product_fields_attributes,请不要忘记为 Porduct 模型定义 Accepts_nested_attributes。
标签: ruby-on-rails ruby validation model