Rails – link_to helper with data-* attribute [duplicate]

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" } }

Leave a Comment