如果一个但不是所有子对象都有效,则阻止父对象保存

时间:2016-01-09 01:03:37

标签: ruby-on-rails validation associations

为具有多个子项的父模型对象提交form_for时,如果只有一个子项有效,则父项仍然保存。

如果只有一个孩子无效,我想阻止保存父对象。

class Order < ActiveRecord::Base
  has_and_belongs_to_many :units
  validates_associated :units
end

class Unit < ActiveRecord::Base
  has_and_belongs_to_many :orders
  validates_numericality_of :quantity, :only_integer => true, :greater_than_or_equal_to => 0
end

当我在订单中有多个单位时,如果有单位。数量&gt; 0,订单记录持续存在,以及那些验证的单位。

1 个答案:

答案 0 :(得分:1)

我尽可能多地传播Why You Don’t Need Has_and_belongs_to_many Relationships的福音。请尝试以下设置:

模型

# Order model
has_many :order_units
has_many :units, through: :order_units
accepts_nested_attributes_for :units
validates_associated :units

# Unit model
has_many :order_units
has_many :orders, through: :order_units
validates_numericality_of :quantity, only_integer: true, greater_than_or_equal_to: 0, allow_blank: true

# OrderUnit model
belongs_to :order
belongs_to :unit

控制器

# OrdersController, new and edit actions
3.times do
    @order.units.build
end

# white listed params
def order_params
    params.require(:order).permit(units_attributes: [:id, :quantity, :_destroy])
end

表单视图

# Order _form partial
<%= f.fields_for :units do |unit| -%>
    <%= content_tag :p, unit.text_field(:quantity) %>
<% end %>

enter image description here