Forum: Ruby on Rails default values for new table entry

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Ben N. (Guest)
on 2009-04-23 02:38
(Received via mailing list)

I would like a new record that is created with the new.html.erb page
to always populate a specific variable with a default value.

The simplest way would be to have a check_box that defaults to checked
when the page is loaded, but this seems to be tricky.

Current code looks something like
form_for(@foo) do |f|
check_box(:f, :this_should_always_be_yes_from_this_form, {}, 1, 0)

1. Can I set this value automatically?
2. Can I get the check box to default to "yes"?

Franco C. (Guest)
on 2009-04-23 07:10
(Received via mailing list)
You can do this in the controller:

@foo = => true)

And then this in the view:

form_for(@foo) do |f|

f.check_box :parameter_name


Franco C..
Ben N. (Guest)
on 2009-04-27 08:22
(Received via mailing list)
this worked great, thanks

Robby R. (Guest)
on 2009-04-27 08:39
(Received via mailing list)
You can do this in the controller, but I'd advise against this.

Why? Business logic is best located and/or managed by the model. The
easiest way to do this would be to modify the database column to set a
default value, which Active Record will read when it looks at the
table structure and use this to set default values.

For example, if you had a migration for a new field, you could do the

add_column :teams, :active, :boolean, :default => false

If we had a Team model, when we did, we'd see that there
would be a default value already set for the active attribute.

As mentioned, this would be the simplest method and would keep the
business logic located in the realm of the model. Keep controller code
short and sweet.

Hope this helps!


On Wed, Apr 22, 2009 at 8:09 PM, Franco C. 
>> The simplest way would be to have a check_box that defaults to checked
>> Thanks,
>> Ben
> >

Robby R.
Chief Evangelist, Partner

design // development // hosting w/Ruby on Rails
aim: planetargon

+1 503 445 2457
+1 877 55 ARGON [toll free]
+1 815 642 4068 [fax]
This topic is locked and can not be replied to.