Q:

How do I add a data attribute to my Rails modal window link?

I’m using Rails 4.2.3 with the jquery-modal-rails gem.  This is so that I can easily spawn modal windows out of a DIV on my page.  I’m trying to create a link to activate the modal window, and I want this link to have a “data-id” attribute so that I can run some JS prior to the modal window opening.  So I tried
<%= link_to_modal "Edit", "#add_form", :class=>'edit_link', :data-id=>my_object_time.my_object.id %>

but I get the error
undefined local variable or method `id' for #<#<Class:0x007fc692bc9ef8>:0x007fc69b0079b8>

It is complaining about the line above (if I remove the “-id” part the link renders, but then I don’t have a data-id attribute).

A:

You should change to this:
<%= link_to_modal "Edit", "#add_form", :class=>'edit_link', "data-id" =>my_object_time.my_object.id %>

That is the syntax, you can not define something like:
{:data-id => my_object_time.my_object.id}

Because when you use :data-id, ruby will understand like:
:data - (minus) id, so - is undefined for symbol, and id also is undefined!
But this will work fine:
{"data-id" => my_object_time.my_object.id}

It is a normal string, in you case, let's use string

