我正在使用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
我在哪裏出了問題,還鎮定,我迷惑插入
[Rails 4 - Strong Parameters - Nested Objects]的可能重複(http://stackoverflow.com/questions/18436741/rails-4-strong-parameters-nested-objects) – emaillenin
'@ newspaper.newspaper_categoried.build'是一個錯字,對嗎? –