Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - Checkbox not saving to database?

I've got a migration which uses a boolean value and generates a checkbox in its view. However, no matter what I click, the value saved to the database is not affected.

My migration looks like this:

def self.up
    create_table :blogposts do |t|
      t.string :title
      t.text :body
      t.boolean :allow_comments, :default => false  
      t.references :author
      t.references :lasteditor
      t.timestamps
    end
  end

My view looks like this:

<% semantic_form_for([:controlpanel, @blogpost]) do |form| %>
<%= form.error_messages %>
<% form.inputs do %>
<%= form.input :title %>
<%= form.input :body %>
<%= form.input :allow_comments %>
<% end %>
<%= form.buttons %>

Which produces the following HTML:

<li class="boolean required" id="blogpost_allow_comments_input">
<label for="blogpost_allow_comments">
<input id="blogpost_allow_comments" name="blogpost[allow_comments]" type="checkbox" value="1" />
<input name="blogpost[allow_comments]" type="hidden" value="0" />Allow comments
<abbr title="required">*</abbr>
</label>
</li> 

The controller is just the default generated by the scaffold.

If I set the default in the migration, that value is always saved in the database. If I do not set a default, it is always NULL.

Can anyone suggest a solution, suggestion on what might be going wrong?

Any advice appreciated.

Thanks.

like image 867
Dan Avatar asked Feb 07 '10 18:02

Dan


2 Answers

Doh, I'd forgotten to set attr_accessible in the model.

like image 144
Dan Avatar answered Oct 23 '22 06:10

Dan


Try using form_for instead of semantic_form_for and replace <%= form.input :allow_comments %> with <%= form.check_box_field :allow_comments %>

like image 38
Simone Carletti Avatar answered Oct 23 '22 06:10

Simone Carletti