Reputation: 10215
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.
Upvotes: 0
Views: 1577
Reputation: 402
Improving upon previous answers, I would suggest moving the method to an InvoiceHelper
# app/helpers/invoices_helper.rb
module InvoicesHelper
def options_for_invoice_select
order(:number).map { |i| [ i.number, i.id, data: {attribute: i.some_attribute} ] }
end
end
And then you can simply send this collection to your select
<%= f.select :invoice_id, options_for_invoice_select %>
Using this directly (instead of calling options_for_select
) avoids a potential errors where the selected option is not selected when editing
Upvotes: 0
Reputation: 17803
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
Upvotes: 3
Reputation: 1745
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
Upvotes: 1