简体   繁体   English

用Rails符号选择设置选项

[英]Set option selected with rails symbol

I've this select in my form: 我在表单中选择了这个:

<%= select_tag :x, options_from_collection_for_select(@dmj, :id, :name, :selected), {class: "form-control"} %>

but when I load the page, the option whose value is set in db is not selected. 但是,当我加载页面时,未选择在db中设置其值的选项。

The symbol :selected comes from a SQL query in the controller and if I try to replace the :name with :selected in the options_from_collection_for_select , I can see that its value is correct. :selected符号来自控制器中的SQL查询,如果我尝试在options_from_collection_for_select中将:name替换为:selected ,我可以看到其值正确。

Also, if I manually set the integer in the options_from_collection_for_select the corresponding option is selected. 另外,如果我在options_from_collection_for_select手动设置整数,则会选择相应的选项。

Why do I not succeed in selecting the option with the symbol? 为什么无法成功选择带有符号的选项?

EDIT: 编辑:

My query is making a join to retrieve the selected from a Join table. 我的查询正在进行联接以从联接表中检索选定的对象。 Here's the query: @dmj = DiscoveryModeInjury.find_by_sql("SELECT D.name, D.id, L.discovery_mode_injury_id AS selected 查询如下:@dmj = DiscoveryModeInjury.find_by_sql(“选择了选择的D.name,D.id,L.discovery_mode_injury_id AS
FROM
discovery_mode_injuries D Discovery_mode_injuries D
LEFT OUTER JOIN 左外连接
link_dismodeinj_hospitalizations L link_dismodeinj_hospitalizations L
ON
D.id = L.discovery_mode_injury_id D.id = L.discovery_mode_injury_id
WHERE 哪里
flag = 'disc' 标志='disc'
ORDER BY 订购
D.name") D.name“)

If I have understood correctly Akash Srivastava's suggestion, the query should return the DiscoveryModeInjury id field? 如果我正确理解了Akash Srivastava的建议,则查询应返回DiscoveryModeInjury id字段? How..? 怎么样..? thanks. 谢谢。

Make sure your query for :selected returns an :id field. 确保对:selected的查询返回:id字段。 Basically, the selected option in options_from_collection_for_select() should be of the same field as the value field of the same, which is :id in your case. 基本上, options_from_collection_for_select()selected选项应该与相同value字段相同,在您的情况下为:id Many of us make this mistake of keeping the result of selected as an object of the collection . 我们中的许多人都犯了这样的错误:将selected的结果保留为collection的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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