Ruby On Rails - 验证控制器中的嵌套参数(不能为零)

时间:2014-04-29 19:42:25

标签: ruby-on-rails ruby nested-attributes

这些是我的参数:

{"utf8"=>"✓", "authenticity_token"=>"0RYiIDDgmOk0gCDRkAgHvv+UIgp/BuU33CLThJXqOTE=", 
    "order"=>
            {"operation_in_orders_attributes"=>
                 {"0"=>{"service_operation_id"=>"5"}, 
                  "1"=>{"service_operation_id"=>""}, 
                  "2"=>{"service_operation_id"=>"4"}, 
                  "3"=>{"service_operation_id"=>""},                 
                  "4"=>{"service_operation_id"=>""}}, 
            "kontakt"=>"comment", "Car_id"=>"50"}, 
                      "commit"=>"Dodaj", 
                      "car_id"=>"dw815gn"}

Order has many operation_in_orders
Order has many service_operations through OperationInOrder
OperationInOrder belongs to Order
OperationInOrder belongs to ServiceOperation
ServiceOperation has many operation_in_orders
ServiceOperation has many orders through OperationInOrder

我的表格:

<%= form_for @order, url: new_car_order_path(@car, @order),  html: {class: "add_order"} do |r| %>
  <%= r.label "Service", class: :add_order_label    %> 
  <% 5.times do %>
  <%= r.fields_for :operation_in_orders do |v| %>

  <%= v.collection_select(:service_operation_id, ServiceOperation.all, :id, :nazwa,include_blank: true) %>
 <!-- <%= v.text_field :order_id, value: @order.id, :style => "display:none" %> -->
  <% end %>
  <% end %>
  <%= r.label "Kontakt", class: :add_order_label %>
  <%= r.text_field :kontakt %>
  <%= r.text_field :Car_id, value: @car.id, :style => "display:none" %>
  <%= r.label " "  %> 
  <%= r.submit "Add", class: "sub" %>
  <%= link_to "Send",ordered_path(car_id: @car.id) ,  class: 'sub'%> 

<% end %>

我有一个表单,我最多可以选择五个ServiceOperations订单并保存 保存时,会生成5个新的OperationInService个对象/行。

如果表单上的相应字段为空,是否有可能不创建这些连接表?

例如:
我只填写了5个领域中的2个。我只保存这两个,而不是5.现在我保存零值......

我尝试在OperationInService模型中验证,但是出现了错误(rails无法识别控制器中的格式)。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

更新accepts_nested_form_for模型中的Order方法调用,如下所示:

class Order < ActiveRecord::Base
  has_many :operation_in_orders
  accepts_nested_attributes_for :operation_in_orders, reject_if: proc { |attributes| attributes['service_operation_id'].blank? }
  ## ..
end

如果operation_in_orders为空,则不会创建service_operation_id的记录。