更新时的嵌套属性验证

时间:2015-08-04 04:14:22

标签: ruby-on-rails ruby validation ruby-on-rails-4

我有两个模型ProductProductBoxing,产品有很多product_boxings。

product.rb

class Product < ActiveRecord::Base
   has_many   :product_boxings
   accepts_nested_attributes_for :product_boxings 
   validates :name, presence: { presence: true, message: 'please give a name' }, on: :update
end

product_boxing.rb

class ProductBoxing < ActiveRecord::Base
   belongs_to :product
   validates :quantity, presence: { presence: true, message: 'please fill in quantity' }, on: :update 
end

_form.html.erb

<%= form_for(@product, html: {class: "form-horizontal", role: "form", multipart: true}) do |f| %>
  <%= f.text_field :name%>
  <%= f.fields_for :product_boxings do |g| %>        
      <%= g.text_field :quantity %>     
  <% end %>     
<% end %>

出于某些原因,我首先创建了productproduct_boxing,但未进行验证。之后,我想验证两者的更新。验证适用于Product,但不适用于ProductBoxing

我的代码有问题吗?或者这是一个铁路问题?

顺便说一下,我删除了验证选项on: :update,并在创建时验证了这两个验证选项。

更新

首先,用户将运行以下代码

 def new
   product = Product.new
   p_b= product.product_boxings.build() 
   product.save!    
   redirect_to edit_product_path(product)
 end

然后

 def edit
 end

并发布表格

 def update
   @product.update(product_params)

   unless @product.errors.any?  
     redirect_to products_url      
   else  
     render 'edit'
   end   
 end

其他信息

def product_params
    params.require(:product).permit(:name, product_boxings_attributes:[:id, :quantity] )
end

1 个答案:

答案 0 :(得分:0)

您应确保验证相关模型:

class Product < ActiveRecord::Base
   has_many   :product_boxings
   validates_associated :product_boxings
   #  ...
end

http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_associated

使用控制台测试模型

> p = Product.new
> p.valid?
> p.errors
> p.product_boxings.each { |pb| pb.valid?; pb.errors }

如果您想在错误列表中看到此product_boxings消息,则应创建自定义验证。

validate :associated_product_boxings

def associated_product_boxings
  product_boxings.each do |product_boxing|
     errors.add (...) unless product_boxing.valid?
  end
end