Default values for new table entry

All,

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”?

Thanks,
Ben

You can do this in the controller:

@foo = Foo.new(:parameter_name => true)

And then this in the view:

form_for(@foo) do |f|

f.check_box :parameter_name

Regards.

Franco C…

this worked great, thanks

–b

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
following:

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

If we had a Team model, when we did Team.new, 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!

Cheers,
Robby

On Wed, Apr 22, 2009 at 8:09 PM, Franco C. [email protected]
wrote:

The simplest way would be to have a check_box that defaults to checked
Thanks,
Ben


Robby R.
Chief Evangelist, Partner

PLANET ARGON, LLC
design // development // hosting w/Ruby on Rails

http://robbyonrails.com/
http://twitter.com/planetargon
aim: planetargon

+1 503 445 2457
+1 877 55 ARGON [toll free]
+1 815 642 4068 [fax]