如果只有一个但不是所有子对象都有效,则阻止父对象保存
Prevent parent object from saving if even one but not all child objects are valid
当为一个有多个子对象的父模型对象提交 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
当我在一个订单中有很多单位时,如果有一个 unit.quantity > 0,订单记录将与那些有效的单位一起保留。
我尽可能多地传播 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 %>
当为一个有多个子对象的父模型对象提交 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
当我在一个订单中有很多单位时,如果有一个 unit.quantity > 0,订单记录将与那些有效的单位一起保留。
我尽可能多地传播 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 %>