Reputation: 544
the forms for creating my polls show up correctly and the poll itself is created, but the answer options are not saved...
I am using rails 5.0.0.1
this is my db :
class CreatePolls < ActiveRecord::Migration[5.0]
def change
create_table :polls do |t|
t.string :question
t.timestamps
end
end
end
-
class CreateAnswerOptions < ActiveRecord::Migration[5.0]
def change
create_table :answer_options do |t|
t.references :poll, foreign_key: true
t.string :text
t.integer :nbvotes, :default => 0
t.timestamps
end
end
end
-
my models :
class AnswerOption < ApplicationRecord
belongs_to :poll
end
-
class Poll < ApplicationRecord
has_many :answer_options, :dependent => :destroy
accepts_nested_attributes_for :answer_options
end
my controller :
# GET /polls/new
def new
@poll = Poll.new
2.times { @poll.answer_options.build }
end
# POST /polls
# POST /polls.json
def create
@poll = Poll.new(poll_params)
respond_to do |format|
if @poll.save
format.html { redirect_to @poll, notice: 'Poll was successfully created.' }
format.json { render :show, status: :created, location: @poll }
else
format.html { render :new }
format.json { render json: @poll.errors, status: :unprocessable_entity }
end
end
end
and my view :
<%= form_for(poll) do |f| %>
<% if poll.errors.any? %>
<div class="row">
<div id="error_explanation">
<h2><%= pluralize(poll.errors.count, "error") %> prohibited this poll from being saved:</h2>
<ul>
<% poll.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<div class="row">
<div class="field form-group">
<%= f.label :question %>
<%= f.text_field :question, :class => 'form-control' %>
</div>
</div>
<div class="row">
<div class="col-md-1">
<!--tab-->
</div>
<div class="col-md-11">
<label for="options">Options</label>
<ul class="list-group">
<%= f.fields_for :answer_options do |builder|%>
<li class="list-group-item">
<%= builder.text_field :text %>
</li>
<% end %>
</ul>
</div>
</div>
<div class="row">
<div class="actions">
<%= f.submit "Create Poll", :class => 'btn btn-primary' %>
</div>
</div>
<% end %>
I can't find why the data is not being saved... I can create them in the rails console ans they get displayed in the show action. I tried playing with adding and removing 's' in the naming of poll or answer_option without success...
Upvotes: 0
Views: 55
Reputation: 471
Can you please use this piece of code. You are required to permit the answer_options_attributes params as it is created by nested attributes automatically.
def poll_params
params.require(:poll).permit(:question, answer_options_attributes: [:text])
end
Upvotes: 1