简体   繁体   中英

checkbox variable in rails always true

I have a rails app where I am using a checkbox on my view to determine which part of my if statement runs. I thought this would be an easy task but even though the response in console after clicking submit button shows both: "adult"=>"0" (when not checked) and "adult"=>"1" (when checked) but if I try

puts @application.adult

the console only prints true

Here's the relevant part of my .html.haml file...this is my most recent attempt

=simple_form_for( :application, :url => users_partner_acceptance_path( application ), :method => :put ) do | f |
  .clearfix
    .column
      =f.input :full_name, label: 'Full Name', placeholder: 'Full Name'
      .help-block * please enter your legal name
      =f.input :address_1, label: 'Address', placeholder: 'Apartment, Street'
      =f.check_box_tag :adult, inline_label: 'I am over 18 years old.', as: :boolean, checked = true
      .guardian
      =f.input :guardian_full_name, label: 'Guardian Full Name', placeholder: 'Full Name'
      =render 'partner_details_errors', application: application
  =f.submit 'Show Contract', class: 'btn btn-primary', data: { 'text' => 'Create Contract', 'disabled-text' => 'Creating ...' } 

I've tried

{:checked=> true}

and

checked: true 

instead of

checked = true

and probably a few others I've tried

=f.check_box :adult 

and

=f.input :adult 

instead of

=f.check_box_tag :adult

In my controller, I'm trying to do something like this:

if @application.adult == true
  # do something
else
  # do something else
end

Any suggestions, help is greatly appreciated. Thanks!

I'm using Rails 3.2.12

check_box_tag(name, value = "1", checked = false, options = {})

If adult is a part of the Application class, then you want f.check_box instead of f.check_box_tag . Otherwise, you should just have check_box_tag... .

= f.label :adult, "I am over 18 years old."

= f.check_box, :adult

Can you post what your params hash looks like when submitted? FYI you don't need to do if @application.adult == true since the if will already be doing that.

<%= f.check_box :hobby, {:multiple => "true"}, "hockeys", nil %>

<%= f.check_box :hobby, {:multiple => "true"}, "cricket", nil %>


这将对您有所帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM