简体   繁体   中英

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.

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.

Also, if I manually set the integer in the options_from_collection_for_select the corresponding option is selected.

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
FROM
discovery_mode_injuries D
LEFT OUTER JOIN
link_dismodeinj_hospitalizations L
ON
D.id = L.discovery_mode_injury_id
WHERE
flag = 'disc'
ORDER BY
D.name")

If I have understood correctly Akash Srivastava's suggestion, the query should return the DiscoveryModeInjury id field? How..? thanks.

Make sure your query for :selected returns an :id field. 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. Many of us make this mistake of keeping the result of selected as an object of the collection .

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