Rails Formtastic: adding “data-” field to option tag

后端 未结 3 912
暖寄归人
暖寄归人 2020-12-06 16:33

I have:

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

I need:

3条回答
  •  一向
    一向 (楼主)
    2020-12-06 17:00

    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:

    
    
    

提交回复
热议问题