2014-01-20 47 views
1

我有以下型號:Rails的嵌套屬性 - 不創建父

class Parent 
    has_many :cars 
    accepts_nested_attributes_for :cars 
end 

class Car 
    belongs_to :parent 
    validates :parent, presence: true 
end 

控制器代碼:

def create 
    parent = Parent.new 
    parent.attributes = parent_params 
    parent.save 
end 

def parent_params 
    params.require(:parent).permit(:name, cars_attributes: [:name]) 
end 

當我嘗試創建一個ParentCars,驗證上失敗Cars,因爲Parent尚未創建。如何通過嵌套屬性創建通過驗證?

回答

2

基於快速搜索,您可以使用:inverse_of來克服這種情況。

在您的代碼:

class Parent 
    has_many :cars, inverse_of: :parent 
    accepts_nested_attributes_for :cars 
end 

class Car 
    belongs_to :parent 
    validates :parent, presence: true 
end 

(未測試)

退房馬克來源:

  1. Validating presence of the parent object(滾動的那部分)。
  2. Issue on github
  3. Some post I didn't bother to read but is referenced on the issue above

GL HF &。

+0

賓果!實際上,'Parent'中的'has_many:cars,inverse_of :: parent'是工作的。謝謝。 –

+0

哇沒有證據讀我的答案。爲了真理的緣故將編輯。 – rlecaro2

+0

@ArtemKalinchuk你是否需要兒童班(汽車)上的'inverse_of'部分? – rlecaro2