Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Radio button tags


  • Please log in to reply
3 replies to this topic

#1 Ohm

Ohm

    Guard

  • Members
  • 184 posts
  • LocationCopenhagen

Posted 25 September 2013 - 12:26 PM

Okay, I'm going truly insane here.

In my controller I set

@active = false

And then in my view I even have

Active: <%= @active %><br>
Yes <%= radio_button_tag "active", true, @active %> 
No <%= radio_button_tag "active", false, !@active %>

However, "Yes" is selected by default, even though @active is false.

 

Looking at the documentation (http://api.rubyonrai...adio_button_tag) and even the code, I believe I'm doing it correct. So what gives?


Blog: http://ohm.sh | Twitter: madsohm


#2 Rowel

Rowel

    Controller

  • Members
  • 109 posts

Posted 25 September 2013 - 02:31 PM   Best Answer

The second parameter is the value.... expecting a string, right? 

 

But you have it listed as true and false.  

 

Have you tried 'true' and 'false' ?  

 

Yes <%= radio_button_tag "active", "true", @active %>

 

where 1st param = "active" = name of radio button

           2nd param = "true" = value of radio button if checked.

           3rd param = if true,  then checked="checked"  

 

Maybe to avoid confusion, you can code it instead as <%= radio_button_tag "active", "yes", @active %>



#3 Ohm

Ohm

    Guard

  • Members
  • 184 posts
  • LocationCopenhagen

Posted 25 September 2013 - 02:41 PM

Nope, this wouldn't work either, as @active now is a string, and every string in Ruby is true.

 

I would've to do

<%= radio_button_tag "active", "true", @active == "true" %>
<%= radio_button_tag "active", "false", @active != "true" %>

which works, but is ugly as...

 

In my controller I also have to rewrite it as

@active = params[:active] == 'true' if params[:active].present?

Blog: http://ohm.sh | Twitter: madsohm


#4 jmesserer

jmesserer

    Passenger

  • Members
  • 4 posts
  • LocationMinneapolis, MN

Posted 30 September 2013 - 05:58 PM

Here's another option ... it allows you to eliminate setting the true/false string in the controller code by using 'true.to_s' or 'false.to_s'. For the sake of testing I just put the 'active' variable in the view but you know it's coming from the controller.

- active = true
= radio_button_tag "active_1", true.to_s, active
= radio_button_tag "active_1", false.to_s, !active

- active = false
= radio_button_tag "active_2", "true", active
= radio_button_tag "active_1", "false", !active






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users