Rails 4 has_many关联表没有建立

时间:2014-04-25 21:51:18

标签: ruby-on-rails-4 associations nested-attributes has-many

也许我还是不明白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

Entry Controller

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

提前致谢。

1 个答案:

答案 0 :(得分:0)

更新表单中的fields_for,如下所示:

   <%= q.fields_for :answers do |a| %>
        <%= a.text_field :content %>
    <% end %>

注意复数:answers而非:answer。 由于Entry模型与1-M关系中的Answer相关联,因此您应该在字段中使用复数:answers

现在,当您使用:answer(单数)时,它没有被rails正确解释,因此您在answer哈希中收到params密钥而不是{{1}显然导致警告为answers_attributes

<强>更新

更新Unpermitted parameters: answer操作,如下所示:

create

它应该是def create @answer = Entry.create(params.require(:entry).permit(:survey_id, answers_attributes: [:content, :entry_id])) redirect_to '/' end 而不是answers_attributes: [:content, :entry_id](注意缺少answers_attributes [:content, :entry_id]

此外,我建议您更新您的Entry Controller :操作,如下所示:

new

更新后def new @entry = Entry.new @entry.answers.build end 如下:

form_for

注意:

控制器名称不符合Rails约定,因此它会弄乱<%= form_for(@entry) do |q| %> 哈希。您没有获得params作为关键字,而是获得了entry。我建议将控制器名称entrie更改为EntrysController。将文件EntriesController重命名为entrys_controller.rb。此外,通过将所有entries_controller.rb替换为routes.rb来更新entrys中特定于此控制器的路由