简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM