114

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' }
Community
  • 1
  • 1
eveevans
  • 4,392
  • 2
  • 31
  • 38

2 Answers2

232

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" } }
Chris Hough
  • 3,389
  • 3
  • 41
  • 80
sethvargo
  • 26,739
  • 10
  • 86
  • 156
  • It works perfectly, May I ask => where did you notice of that :data syntax? – eveevans Jan 04 '12 at 22:19
  • 1
    I think it was in a [Railscast](http://railscasts.com)? I'm not sure. I've been using it for awhile. It's defined in the Rails source if you want to poke around. – sethvargo Jan 04 '12 at 22:20
  • 6
    I'd like to point here for future visitors that with the new Ruby 1.9 syntax, only the first method works. So, you can do this: data: { type: 'remote' } but not this: 'data-type': 'remote' – Ashitaka Jun 19 '12 at 18:40
  • 2
    For Rails 3.0.9 specifically, you have to use the direct route with `:'data-foo'`. I might be doing something wrong, but using the `:data => {}` method was putting the hash directly into the HTML. – John Sep 16 '12 at 10:01
  • data: { foo: {bar: 'that' } –  Sep 12 '13 at 21:14
  • The gotcha is actually that underscored entities are dasherized automatically. :data => { :foo_bar => 'that' } becomes data-foo-bar="that". No need to quote the symbols. – stephencelis Oct 29 '13 at 19:16
7

Add a data- attribute by doing the following:

link_to "Hello", hello_path, :"data-attribute" => "yeah!"
jackyalcine
  • 469
  • 1
  • 8
  • 21
Robin
  • 21,667
  • 10
  • 62
  • 85