I want to use select form elements to choose between boolean options. How can I have it default to true and still display the persisted value (either true or false) when editing an existing object? I guess booleans default to false by default so its not obvious how to recognize when it's a real 'false' that the user set or default false because the value was null. thanks
on 2006-03-10 17:45
on 2006-03-10 18:01
On Fri, 2006-03-10 at 11:43 -0500, Larry White wrote: > I want to use select form elements to choose between boolean options. > How can I have it default to true and still display the persisted > value (either true or false) when editing an existing object? I guess > booleans default to false by default so its not obvious how to > recognize when it's a real 'false' that the user set or default false > because the value was null. --- controller def new Animal.new :my_boolean_field = true end model YES_NO = [ [ "Yes", true ], [ "No", false ] ].freeze view <%= options = [['prompt?', '']] + Animal::YES_NO select("amimal", "my_boolean_field", options) %> Craig
on 2006-03-10 19:01
Maybe I'm being too literal but I'm getting an uninitialized constant error for Animal::YES_NO. My guess is that i'm missing something obvioius in the constant declaration. It's at the top of the model, does it need an explicit public declaration?
on 2006-03-10 19:23
I was just guessing that you have a class named Animal - you would have to adjust for whatever class it is that you are using... i.e. models/animal.rb class Animal < ActiveRecord::Base def YES_NO ... end I think I referenced the 'Animal' class elsewhere, you would have to adjust those too. Craig
on 2006-03-10 19:42
it can't see the constant. do i have to declare in the view that i'm using Animal?
on 2006-03-10 19:51
I'm trying to suggest that you put it into whatever class you are using and substitute that class name for Animal wherever I referenced the Animal class. I thought by using 'Animal' class it would make it more meaningful to you. In my case, I am in placements_controller (and using Placement Class) thus in my Placement class (models/placement.rb) YES_NO = [ [ "Yes", true ], [ "No", false ] ].freeze and in my view... <%= options = [['Accepted?', '']] + Placement::YES_NO select("placement", "accepted", options) %> (where 'accepted' is the boolean) and in my placements_controller.rb, I might have code like... def new @placement = Placement.new @placement.accepted = true end the controller code assigns a 'default' value of true to the 'new' Placement Craig
on 2006-03-10 20:00
I did that, but it doesn't work. I have no idea why. I embedded the array in the view directly -- <%= options = [["Yes", true]... and that works. It's not as clean but it will do for now. Thank you very much for your help.