简体   繁体   中英

Rails collection_select is not accepting a :selected option

I'm using a collection_select to display the contents of a hash:

Hash

CATEGORY1_TEXT_STYLE = {
  'Normal' => 'normal',
  'Normal Centered' => 'normal center',
  'Bold' => 'bold'
  ...
}

Collection Select

= collection_select :category1_style1, :first, Homepage::CATEGORY1_TEXT_STYLE, :last, :first, options = { :selected => style_selected(@style.first) }

style_selected (from helper)

def style_selected(value)
  returnval = ''
  Homepage::CATEGORY1_TEXT_STYLE.each { |key, val| returnval = key if val == value }
  returnval
end

Controller

@style = Homepage.find(0).category1_style.gsub('-', '').split("\n")[1..-1]

This outputs: [" bold center", " blue center", " normal center", " blue center"]

It's confusing because I'm not sure how to get it to choose a selected value based on that hash. I've done it before using id values (numbers) and it works, but this key/value pair is both strings and the :selected => "" field doesn't seem to want to take a string to match again, whether it's a match for the key or the value (I've tried both).

Any insight on trying to have a collection select display a default selected value when dealing with strings?

Thanks!

The answer is here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select#632--selected

If you want some object to be selected by default, be sure to use its id, not the whole object.

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