문제

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.

도움이 되었습니까?

해결책

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

다른 팁

This explains it very well: https://stackoverflow.com/a/9076805/2036529

In your view, you can use:

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

and in your Invoice class, change the method to following:

def self.numbers_ordered
   order(:number).map { |i| [ i.number, i.id, {'data-customAttr': "#{i.attr_1} -- #{i.attr_2}" ] }
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top