2016-01-09 26 views
0

當爲具有多個子對象的父模型對象提交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,則爲了記錄仍然存在,與那些驗證單元一起。

+0

你可以添加你當前型號的代碼? – kjmagic13

+0

當然是......見上面。 – MarkD

回答

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

+0

是的,謝謝。這是我最終使用的解決方案。 has_many通過更容易。 – MarkD

+0

@MarkDRubyist,請您將此標記爲將其關閉的答案。 – kjmagic13

相關問題