如何将嵌套的表单值插入到DB中

时间:2014-04-12 09:39:47

标签: ruby-on-rails ruby ruby-on-rails-4 nested-forms

我正在使用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

如果我出错了,我仍然很难插入

1 个答案:

答案 0 :(得分:3)

更新此

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