Search code examples
ruby-on-railsbooleanscaffolding

Why do I get the error "undefined method 'merge' for true:TrueCLass" when adding a checkbox in Rails


I am very new to development and was hoping someone could assist:

I receive the error "undefined method 'merge' error when I include the following checkbox:

<%= f.check_box :is_female, true %> <%= f.label :is_female, "Female" %>    
<%= f.check_box :is_female, false %> <%= f.label :is_female, "Male" %> 

The above code is in the profiles folder which I created using the following:

$ rails generate scaffold profiles description:string

I then generated the following migration:

$ rails generate migration add_websites_to_profiles website:string

This created the migrate file *************_add_website_to_profiles.rb

Here is the add_websites_to_profiles.rb:

class AddWebsiteToProfiles < ActiveRecord::Migration
  def change


  add_column :profiles, :website, :string
  add_column :profiles, :is_female, :boolean, default: false
  end
end

I manually added the following:

add_column :profiles, :is_female, :boolean, default: false

I receive the error when I have the true and false command in the checkbox. When I remove true false it appears on the page with no error, but it is not saved to db.


Solution

  • You are getting mixed up between two ways of generating a check box I think.

    The form builder version, f.check_box, you are using expects a hash as the second parameter. You'd need to call f.check_box(:is_female, {}, true) for a value of true.

    check_box_tag on the other hand does expect a value as the second parameter. You could use check_box_tag(:is_female, true) instead.

    However, as @Santosh points out in the comments, you'd probably be better off having a pair of radio buttons if you want the object to be either male or female.