2014-04-12 99 views
0

我正在使用Rails 4.如何將嵌套表單值插入到數據庫中

在我的項目中,包含has_many關係的嵌套表單。從UI的角度來看,我明白了。但嵌套的表單值不會插入到數據庫中。

class Newspaper < ActiveRecord::Base 
    has_to :newspaper_categories, :dependent_destroy => true 
    accepts_nested_attributes_for :newspaper_categories, :allow_destroy => true, :reject_if => :all_blank 
end 

class NewspaperCategory < ActiveRecord::Base 
    belongs_to :newspaper 
end 

報紙形式的內容一樣,

<%= nested_form_for(@newspaper) do |f| %> 

    # Newspaper form fields 

    # Include `Newspaper category` form from the file. 
    <%= f.fields_for :newspaper_categories do |nc|%> 
     <%= render "newspaper_category" %> 
    <% end %> 

    # For add new form using JS 
    <%= f.link_to_add "Add New", :newspaper_categories %> 

    <%= f.submit %> 
<% end %> 

在我的報紙控制器,

# add build in new method, 
def new 
    @newspaper = Newspaper.new 
    @newspaper.newspaper_categoried.build 
end 

# In params set task_attributes, 
def newspaper_params 
    params.require(:newspaper).permit(:name, :logo, task_attributes[:cat_link, :_destroy]) 
end 

我在哪裏出了問題,還鎮定,我迷惑插入

+0

[Rails 4 - Strong Parameters - Nested Objects]的可能重複(http://stackoverflow.com/questions/18436741/rails-4-strong-parameters-nested-objects) – emaillenin

+0

'@ newspaper.newspaper_categoried.build'是一個錯字,對嗎? –

回答

3

更新此

params.require(:newspaper).permit(:name, :logo, {newspaper_categories_attributes: [ :_destroy, :category_id, :rss_link, :image_url]}) 
+0

剛剛更新了答案 –

+0

看到我有一個疑問,在我的'newspaper_category'表中有'4個字段(包括父母的newspaper_category(newspaper_id))'。這是否也需要在'newspaper_categories_attributes' – Ranjith

+0

你不需要'newspaper_id'只需'NewsPaper.new(paper_params).save'報表id將自動分配 –

相關問題