开发者

Rails Formtastic: adding "data-" field to option tag

I have:

form.input :duration, as: select, collection: {}

I need:

<option value="" data-price="XXX"><开发者_开发技巧/option>

Rails does not support HTML5 data attributes for the option tag. Formtastic suggests to create a helper method for this.

Formtastic readme describes how to extend input tags. However, in select_input.rb I can't find any method which would affect the option tag. So, how do I do this?

Also, I found enhanced_select gem which does exactly what I need, but I am not able to make it work with formtastic.


Actually rails does support adding any kind of html tag to options. Usually you would have:

options_for_select( [['First', 1], ['Second', 2]] )

which would give you

<option value="1">First</option>
<option value="2">Second</option>

If you add a hash into the arrays for each option the hash keys/values will be added as HTML attribute to the option, e.g.

options_for_select( [['First', 1, {:'data-price' => 20}],
                     ['Second', 2, {:'data-price' => 30}]] )

will produce the required tags:

<option value="1" data-price="20">First</option>
<option value="2" data-price="30">Second</option>


Assuming you have a model called Items, you can actually do this in formtastic like so:

form.select :duration, 
           collection: Items.map{|item| [item.name, item.id, {"data-price" => item.price}]}

Essentially what you are doing is passing an array of arrays where the final value in each array is a hash. E.g.

[  
  ['Item 1', 1, {"data-price" => '$100'}],   
  ['Item 2', 2, {"data-price" => '$200'}]
]

Rails 3+ (perhaps 2.x - I didn't confirm) will use the hash in such as array and simply add it to the html of the option tag. Giving you the following:

<option data-price="$100" value="1">Item 1</option>
<option data-price="$200" value="2">Item 2</option>


options_for_select([
  ['Item 1', 1, data:{price: 121, delivery: 11}],
  ['Item 2', 2, data:{price: 122, delivery: 22}]
])

Produces

<option data-delivery="11" data-price="121" value="1">Item 1</option>
<option data-delivery="22" data-price="122" value="2">Item 2</option>

Advantage

Using data:{...} is more concise and if using multiple data tags can save code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜