简体   繁体   中英

rails 4 select with selected option not working

In my rails 4 form, I have one field to select values.

<%= f.select(:owner_user_id, Item.find(session[:login_users_item_id]).try(:users).order_by_fullname.collect {|u| [ u.full_name, u.id ] } , {:selected =>  current_user.full_name} )%>

But, the above selected option not showing the above value. In console that value is getting properly.Now,The first item is showing in the select box.

How can I get the value in the selected option as the default value?

The third argument to f.select method is the selected value, and there you can pass the value that you would like to see selected. In your case: current_user.full_name

<%= f.select(:owner_user_id, Item.find(session[:login_users_item_id]).try(:users).order_by_fullname.collect {|u| [ u.full_name, u.id ] }, current_user.full_name)%>
<%= f.select(:owner_user_id, Item.find(session[:login_users_item_id]).try(:users).order_by_fullname.collect {|u| [ u.full_name, u.id ] }, selected: f.object.owner_user_id)%>

尝试这个

You can also use options_for_select helper.

Example :

<%= f.select :owner_user_id, options_for_select(Item.find(session[:login_users_item_id]).try(:users).order_by_fullname.pluck([ :full_name, :id ]), f.object.owner_user_id) %>

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