iand675
iand675

Reputation: 1118

How do you set the default value of a field or set of choices in a rails form?

I'm trying attempting the (ought to be) simple feat of setting a radiobox pair in a Rails form_for block to default to "1 hour" when given the choice between "1/2 hour" or "1 hour" as options. The documentation that I've looked at doesn't indicate how to do this. Any advice?

Upvotes: 1

Views: 2019

Answers (2)

aceofspades
aceofspades

Reputation: 7586

Make sure you're passing an instance to form_for, and that its attribute is pre-set.

@post = Post.new :time => "1 hour"

Then in your view

form_for @post do |f|
  f.radio_button :time, "1/2 hour"
  f.radio_button :time, "1 hour"
end

If this is not a db attribute, do this instead:

form_for @post do |f|
  f.radio_button :time, "1/2 hour"
  f.radio_button :time, "1 hour", {:checked => true}
end

Upvotes: 3

vise
vise

Reputation: 13373

I think the easiest way is to put that value inside your controller.

For example:

def new
  @entry = Entry.new(:radio_box_attribute => 'my default value') # 1 hour
end

Upvotes: 0

Related Questions