Options_for_select - 如何选择数据库中的内容?
我有一个复杂的表单(如 Ryan B 的 Complex Form Railscasts),其中同时更改了几个级别的数据库表。
该下拉框的代码的工作原理是将正确的整数传递到数据库。但是,尽管进行了多次尝试,我仍无法让它正确反映数据库的当前值。我该如何整理这段代码?
<%= o.select :weighting, options_for_select([
["Correct", "4", {:class=>"bold"}],
["Good", "3"],
["Average", "2"],
["Poor", "1"],
["Incorrect", "0", {:class=>"bold"}] ], :weighting), {},
html_options = {:class => "listBox", :style=>"float:left;"} %>
谢谢。
I have a complex form (like Ryan B's Complex Form Railscasts) where I have a few levels of database tables being altered at the same time.
The code for this dropdown box works in that it delivers the correct integer to the database. But, despite numerous attempts I cannot get it to correctly reflect the database's CURRENT value. How can I sort out this code?
<%= o.select :weighting, options_for_select([
["Correct", "4", {:class=>"bold"}],
["Good", "3"],
["Average", "2"],
["Poor", "1"],
["Incorrect", "0", {:class=>"bold"}] ], :weighting), {},
html_options = {:class => "listBox", :style=>"float:left;"} %>
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你走在正确的轨道上,但还没有完全实现。
而
options_for_select
的最后一个参数应该是所选选项的值。您提供的值:weighting
是一个与任何给定选项的值都不匹配的符号。您需要提供实际值。如果您使用实例对象来构建表单,如
您可以简单地使用
@whatever.weighting.to_s
,如:否则,有一种方法可以将对象从表单块变量 o 中获取。但这会扰乱内部结构,而内部结构可能会随着升级而改变。
编辑:如果您正在处理多个部分的字段,则可以使用对象访问器从表单构建器块变量中获取特定对象。
重用上面的示例,类似这样使用表单的该实例部分中每个子实例的当前权重。
这也可以用在部分中。
You're on the right track, but not quite there.
While the final argument to
options_for_select
should be the value of the selected option. The value you supply:weighting
is a symbol that does not match the value of any of your given options.You will need to give the actual value. If you used an instance object to build the form as in
You can simply used
@whatever.weighting.to_s
as in:Otherwise, there's a way to get the object off the form block variable o. But that's messing with internals which may change with an upgrade.
Edit: In the case where you're working with fields for and multiple partials, you can get the particular object off of the form builder block variable.with the object accessor.
Reusing the above example something like this to use the current weighting of each child instance in that instance's section of the form.
This can also be used in partials.
第二次尝试 =)
Second try =)