Rails - link_to helper with data-* attribute

Ruby on-RailsRuby on-Rails-3Html

Ruby on-Rails Problem Overview


> Possible Duplicate:
> Best way to use html5 data attributes with rails content_tag helper?

How can I use html5 data-* attrubute in my link_to helper (Rails)

The API says that I have to use this format link_to(body, url, html_options = {}) but I have an error when I put it in html_options

Ex:

link_to "whatever", @whatever_path, { class: 'my_class', data-tooltip: 'what I want' }

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Just pass them in... Rails has a default :data hash

= link_to body, url, :data => { :foo => 'bar', :this => 'that' }

One gotcha - you must surround symbols with quotes if they include a dash:

:data => { :'foo-bar' => 'that' }

Update: In Rails 4, underscores are automatically converted to dashes, so you can do this:

:data => { :foo_bar => 'that' }

Alternatively you can just write it directly:

= link_to body, url, :'data-foo' => 'bar', :'data-this' => 'that'

Update 2: As pointed out in the comments, Ruby 1.9+ allows this syntax, which is now the preferred formatting:

{ data: { foo: "bar" } }

Solution 2 - Ruby on-Rails

Add a data- attribute by doing the following:

link_to "Hello", hello_path, :"data-attribute" => "yeah!"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioneveevansView Question on Stackoverflow
Solution 1 - Ruby on-RailssethvargoView Answer on Stackoverflow
Solution 2 - Ruby on-RailsRobinView Answer on Stackoverflow