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:
<%= @poll.title %>
<%= form_for [ @poll, @reply ] do |f| %>
<%= f.fields_for :answers do |c| %>
<%= render c.object.question.kind, c: c %>
<% end %>
<%=f.submit ‘Finish poll’, class: ‘btn btn-primary’%>
<% end %>
and the partial for the checkbox:
<%= c.label :value, c.object.question.title %>
<%= check_box_tag( 'possible_answer_id['+ possible_answer.id.to_s+']', possible_answer.id) %> <%= possible_answer.title %> <%= c.hidden_field :question_id %>
<% end %>and the partial for the radio buttons:
<%= c.label :value, c.object.question.title %>
<%= c.radio_button :possible_answer_id, possible_answer.id %> <%= possible_answer.title %> <%= c.hidden_field :question_id %>
<% end %>This is my data base model:
https://lh3.googleusercontent.com/-p-nacDnZds8/VmXPoMH4c1I/AAAAAAAAPB8/LpKFndQGNeE/s1600/1-Home.png
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!