如何在 Rails 表单中设置字段或选项集的默认值?

发布于 2024-10-05 13:03:19 字数 108 浏览 0 评论 0原文

我正在尝试(应该是)简单的技巧,在 Rails form_for 块中设置单选框对,当选择“1/2 小时”或“1 小时”作为选项时,默认为“1 小时”。我看过的文档没有表明如何执行此操作。有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

飘然心甜 2024-10-12 13:03:20

确保您将一个实例传递给 form_for,并且其属性已预先设置。

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

然后在您看来,

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

如果这不是 db 属性,请改为执行以下操作:

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

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
对你的占有欲 2024-10-12 13:03:20

我认为最简单的方法是将该值放入控制器中。

例如:

def new
  @entry = Entry.new(:radio_box_attribute => 'my default value') # 1 hour
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文