Search code examples
ruby-on-rails-3formsformtastic

undefined method `collection_check_boxes'


I'm trying to make an invoicing app. The form to create an invoice should include a collection of check boxes so the user can choose which lessons to invoice, but I'm getting this error: undefined method 'collection_check_boxes'.

Here are the models involved:

class Lesson < ActiveRecord::Base
  attr_accessible :lesson_time, :lesson_date, :invoice_id
  belongs_to :invoice
end

class Invoice < ActiveRecord::Base
  attr_accessible :amount, :due_date
  has_many :lessons
end

And the view:

<%= form_for(@invoice) do |f| %>
    <fieldset>     
        <%= f.label :lessons %>   
        <%= f.collection_check_boxes(:lessons, Lesson.all, :id, :lesson_date) %>         
    <%= f.submit %>
    </fieldset>
<% end %>

Solution

  • collection_check_boxes is not a method of form_builder. Either put:

    <%= collection_check_boxes(:lessons, Lesson.all, :id, :lesson_date) %>
    

    This will generate html which won't associate with your model (you won't be able to use MyModel.new(params[my_model]) and expect to get proper response. You would either have to manually call my_model.lessons = params[:lessons] or you can pass a html name parameter to conform your check box name to rails convention).

    Or, if you are using formtastic as you tagged it, you can use this:

    <%= f.input :lessons, :as => :check_boxes, :collection => Lesson.all %>