Help on getting multiple answers on a polls app

20 views
Skip to first unread message

João Belo

unread,
Dec 7, 2015, 2:09:34 PM12/7/15
to Ruby on Rails: Talk
Hello community,

I'm working on a polls app and the the user would answer to 3 types of questions:
Open answers;
Multiple Choice with only one option to select (radio buttons);
Multiple Choice with many options to select (checkboxes).

i've already done the first and the second type of question, but i'm struggling with the checkboxes.

This are my models:

answer.rb

class Answer < ActiveRecord::Base
belongs_to :reply
belongs_to :question
belongs_to :possible_answer
end

poll.rb

class Poll < ActiveRecord::Base
validates_presence_of :title

has_many :questions
has_many :replies
end

possible_answer.rb

class PossibleAnswer < ActiveRecord::Base
belongs_to :question
end

question.rb

class Question < ActiveRecord::Base
belongs_to :poll

has_many :possible_answers
has_many :answers

accepts_nested_attributes_for :possible_answers, reject_if: proc { |attributes| attributes['title'].blank? }
end

reply.rb

class Reply < ActiveRecord::Base
belongs_to :poll
has_many :answers

accepts_nested_attributes_for :answers
end


In the views I have a reply/new.html.erb that already work for radio and open answer questions, by rendering the partial by kind:

<h1><%= @poll.title %></h1>

<%= form_for [ @poll, @reply ] do |f| %>
<%= f.fields_for :answers do |c| %>
<%= render c.object.question.kind, c: c %>
<% end %>
<p>
<%=f.submit 'Finish poll', class: 'btn btn-primary'%>
</p>
<% end %>

and the partial for the checkbox:

<p>
<%= c.label :value, c.object.question.title %>
</p>
<div class="checkbox">
<% c.object.question.possible_answers.each do |possible_answer| %>
<p>
<label>
<%= check_box_tag( 'possible_answer_id['+ possible_answer.id.to_s+']', possible_answer.id) %>
<%= possible_answer.title %>
<%= c.hidden_field :question_id %>
</label>
</p>
<% end %>
</div>

and the partial for the radio buttons:

<p>
  <%= c.label :value, c.object.question.title %>
</p>
<div class="radio">
<% c.object.question.possible_answers.each do |possible_answer| %>
<p>
<label>
<%= c.radio_button :possible_answer_id, possible_answer.id %>
<%= possible_answer.title %>
<%= c.hidden_field :question_id %>
</label>
</p>
<% end %>
</div>

This is my data base model:

for now i can reply to a poll and answer to the 3 kind of questions but the checkboxes kind won't save to the answers table

Probably I have to use has_many through association in the answers model but I'm not getting how. Can someone help me?

Thanks!


Reply all
Reply to author
Forward
0 new messages