ruby on rails f.select options with custom attributes

后端 未结 5 1627
一个人的身影
一个人的身影 2020-11-28 01:34

I have a form select statement, like this:

= f.select :country_id, @countries.map{ |c| [c.name, c.id] }

Which results in this code:

5条回答
  •  忘掉有多难
    2020-11-28 02:01

    This is not possible directly with Rails, and you'll have to create your own helper to create the custom attributes. That said, there are probably two different ways to accomplish what you want:

    (1) Using a custom attribute name in HTML5. In HTML5 you are allowed to have custom attribute names, but they have to be pre-pended with 'data-'. These custom attributes will not get submitted with your form, but they can be used to access your elements in Javascript. If you want to accomplish this, I would recommend creating a helper that generates options like this:

    
    

    (2) Using values with custom splitting to submit additional data. If you actually want to submit the currency-code, I would recommend creating your select box like this:

    = f.select :country_id, @countries.map{ |c| [c.name, "#{c.id}:#{c.currency_code}"] }
    

    This should generate HTML that looks like this:

    
    
    

    Which you can then parse in your controller:

    @id, @currency_code = params[:country_id].split(':')
    

提交回复
热议问题