0

我的accep_nested_attributes_for僅保存父項而不保存子項(嵌套)屬性。這是父母與孩子之間的許多關係。accep_nested_attributes_for未將子屬性保存到數據庫

問題:什麼也沒有發生,也沒有保存。但是在頁面上,我得到這個消息:

utf8: "\xE2\x9C\x93" 
authenticity_token: 9Pjxt7e5RRgWVGafRyMoDqBSqmtj/R2zBSiVxGGxFOI= 
parent: !map:ActiveSupport::HashWithIndifferentAccess 
name: "Test" 
gender: Male 
children_attributes: !map:ActiveSupport::HashWithIndifferentAccess 
"0": !map:ActiveSupport::HashWithIndifferentAccess 
    email: [email protected] 
commit: Submit 

從味精在我的終端的日誌,我認爲這是因爲children_attributes從來沒有得到保存爲它分配一個「0」?這是終端MSG:

Started POST "/parents" for 127.0.0.1 at 2011-09-14 11:14:14 -0400 
Processing by ParentsController#create as HTML 
Parameters: {"utf8"=>"✓", "authenticity_token"=>"9Pjxt7e5RRgWVGafRyMoDqBSqmtj/R2zBSiVxGGxFOI=", "parent"=>{"name"=>"123", "gender"=>"Male", "children_attributes"=>{"0"=>{"email"=>"[email protected]"}}}, "commit"=>"Submit"} 
SQL (0.1ms) BEGIN 
SQL (0.6ms) SELECT 1 FROM `children` WHERE (LOWER(`children`.`email`) = LOWER('[email protected]')) LIMIT 1 
SQL (0.2ms) ROLLBACK 

控制器 -

def new 
    @parent = Parent.new 
    @parent.children.build 
end 

def create 
    @parent = Parent.new(params[:parent]) 
    if @parent.save 
    redirect_to root_path 
    else 
    render 'new' 
    end 
end 

父模型 -

attr_accessible :children_attributes 
has_many :children, :through => :parent_child_relationships 

accepts_nested_attributes_for :children 

兒童模型 -

has_many :parents, :through => :parent_child_relationships 
validates :email, :name, :presence => true 

父形式視圖 -

<%= form_for(@parent, new_parent_path) do |f| %> 

<div> 
    <%= f.label(:name) %></br>  
    <%= f.text_field(:name) %> 
</div> 

<div> 
    <%= f.label(:gender) %> <br/> 
    <%= f.select(:gender, ['Male', 'Female']) %> 
</div> 

    <%= f.fields_for :children do |ff| %> 

    <div> 
    <%= ff.label(:email)%></br> 
    <%= ff.text_field(:email)%> 
    </div> 

    <% end %> 

    <%= submit_tag "Submit" %> 
<% end %> 

任何幫助將不勝感激!謝謝!

回答

0

檢查是否有對兒童模型中的任何失敗驗證

您可以驗證上創建,使用類似下面

 
    validates_uniqueness_of :xxxx, :on => :create 
+0

就是這樣。我有一些驗證,當用戶自己創建一個孩子(而不是通過嵌套關聯)。有沒有一種方法可以使這些驗證僅在創建子本身時有效,並且在它是嵌套屬性的一部分時忽略這些驗證?謝謝 – noob

+0

上面編輯了我的回覆。 –

+0

我認爲通過使用新的代碼@ parent.children.build,您是否有效地創建了新的子對象?我有我的孩子模型中的其他validates_presence,所以即使我這樣做,:on => create,是否仍然不會通過驗證?我現在清理了我的驗證,所以這僅僅是爲了我自己的知識。 – noob

0

你能對兒童模特更改驗證到:

validates :name, :presence => true 
validates :email, :presence => true, :email => true 

然後看看能否爲你解決這個問題嗎?

+0

感謝克里斯蒂安,它看起來像是因爲有一堆其他驗證和has_many:通過它阻止保存的關聯... – noob