Question

Maybe I still do not understand how Rails 4 works with has_many and belongs_to association.

My form doesn't save the has_many relationship

Entry Model

class Entry < ActiveRecord::Base
    belongs_to :survey
    has_many :answers, :dependent => :destroy
    accepts_nested_attributes_for :answers
end

Answer Model

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

<%= 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 %>

Debug error

Parameters: {"utf8"=>"✓", "authenticity_token"=>"**********************=", "entry"=>{"survey_id"=>"1", "answer"=>{"content"=>"asdasd"}}, "commit"=>"Save"}
Unpermitted parameters: answer
(0.1ms)  begin transaction

Thanks in advance.

Was it helpful?

Solution

Update fields_for in your form as below:

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

Note pluralized :answers and not :answer. As Entry model is associated to Answer in a 1-M Relationship, you should be using plural :answers in fields for.

Right now as you used :answer (singular), it wasn't interpreted by rails correctly, so you received answer key in params hash instead of receiving answers_attributes which obviously resulted in warning as Unpermitted parameters: answer

UPDATE

Update the create action as below:

def create
    @answer = Entry.create(params.require(:entry).permit(:survey_id, answers_attributes: [:content, :entry_id]))
    redirect_to '/'
end

It should be answers_attributes: [:content, :entry_id] and not answers_attributes [:content, :entry_id] (Notice missing :)

Also, I would suggest you to update your Entry Controller new action as below:

def new
  @entry = Entry.new
  @entry.answers.build
end

After this update the form_for as below:

<%= form_for(@entry) do |q| %>

NOTE:

The controller name is not as per Rails convention so it is messing up the params hash. Instead of getting entry as a key, you are getting entrie. I would recommend changing the controller name EntrysController to EntriesController. Renaming the file entrys_controller.rb to entries_controller.rb. Also, update the routes specific to this controller in routes.rb by replacing all occurrences of entrys with entries

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top