【发布时间】:2014-04-25 21:51:17
【问题描述】:
也许我仍然不明白 Rails 4 如何与 has_many 和 belongs_to 关联一起工作。
我的表单没有保存 has_many 关系
入门模型
class Entry < ActiveRecord::Base
belongs_to :survey
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers
end
答案模型
class Answer < ActiveRecord::Base
belongs_to :entry
validates :content, presence: true
validates :entry_id, presence: true
end
入口控制器
def create
@answer = Entry.create(params.require(:entry).permit(:survey_id, answers_attributes [:content, :entry_id]))
redirect_to '/'
end
表格
<%= form_for(:entry, :url => {:controller => 'entrys', :action => 'create'}) do |q| %>
<%= q.hidden_field :survey_id, :value => @survey.id %>
<%= q.fields_for :answer do |a| %>
<%= a.text_field :content %>
<% end %>
<%= q.submit :Save %>
<% end %>
调试错误
Parameters: {"utf8"=>"✓", "authenticity_token"=>"**********************=", "entry"=>{"survey_id"=>"1", "answer"=>{"content"=>"asdasd"}}, "commit"=>"Save"}
Unpermitted parameters: answer
(0.1ms) begin transaction
提前致谢。
【问题讨论】:
标签: ruby-on-rails-4 associations nested-attributes has-many