ruby-on-railsrubyruby-on-rails-3custom-data-attribute

How to add a data-attribute to each option of my select box?


In my Rails app I have this select box:

<%= f.select :invoice_id, current_user.invoices.numbers_ordered %>

This is my Invoice class:

class Invoice < ActiveRecord::Base

  belongs_to :user

  def self.numbers_ordered
    order(:number).map { |i| [ i.number, i.id ] }
  end

  ...

end

How can I add a data-attribute to each option without changing too much of my existing code?

Thanks for any help.


Solution

  • You can try something like this:

    def self.numbers_ordered
      order(:number).map { |i| [ i.number, i.id, :'data-attribute' => i.some_data ] }
    end
    

    select uses options_for_select inside and takes all the parameters for options_for_select.

    See Rails API for select, options_for_select, and the comment in options_for_select