jeudi 3 décembre 2015

Ruby on rails - adding multiple choice checkboxes - ERROR - undefined method `check_box_tag'

I'm tying do add a new kind of answers to my polls app. It will be a multiple choice with checkboxes. The user can choose one or more possible answers from the checkboxes presented. I'm struggling to make it work, i'm getting the error:

NoMethodError in Replies#new

undefined method `check_box_tag' for #<ActionView::Helpers::FormBuilder:0x007fae8bd82f48>

right i have this 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>                                                                 
          <%= c.check_box_tag :possible_answer_id, possible_answer.id %>        
          <%= possible_answer.title %>                                          
          <%= c.hidden_field :question_id %>                                    
        </label>                                                                
      </p>                                                                      
  <% end %>                                                                     
</div> 

Probably i have to use has_and_belongs_to_many association in the answers model but i'm not getting how. Can anyone help me?

Thanks everyone!




Aucun commentaire:

Enregistrer un commentaire