【问题标题】:Nested attributes validation on updating更新时的嵌套属性验证
【发布时间】:2015-08-04 04:14:22
【问题描述】:

我有两个型号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

【问题讨论】:

  • 您可以发布生成的参数日志吗?您能确认product_boxing 正在正常更新吗?
  • 你可以在问题中发布strong_params方法吗?
  • 请在问题中..
  • 我发现了一个新情况,如果数量已经填写,数量的验证工作。

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


【解决方案1】:

您应该确保您的关联模型得到验证:

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

【讨论】:

  • 是的,它可以工作,但它显示 validates_associated :product_boxings 的默认错误消息“无效”,而不是 validates :quantity, presence: {存在: true, message: '请填写数量' }, on: :update
  • 您可以在控制台中看到完整的错误列表。我已经更新了我的答案。如果存在验证在列表中,则它工作正常。认为它以安全顺序进行验证。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多