Search code examples
ruby-on-railslink-to

Rationale for :confirm being nested within :data in link_to for Rails


In link_to, :confirm is nested within :data, rather than being a direct key/value pair in options. What's the rationale for this? I suspect it's something to do with data attributes, but I don't know beyond this.

Would this approach allow someone to have a confirmation prompt if they manually added a link that had 'data-confirm="Message" in it?


Solution

  • In the early days the :confirm option was not nested inside data and the implementation was different than today. In fact, when the option was passed, Rails injected an onclick confirm action directly in the HTML tag itself.

    However, in Rails 3 the core team decided to take the direction of unobtrusive javascript. As part of that, all the events that in the past resulted in JavaScript injected directly in the HTML tag (including for example the remote submission of a form or the emulation of the PUT/DELETE HTTP methods) were converted into a solution based on the HTML data attributes and events properly attached to the objects using the Rails UJS file.

    The :confirm option was then converted into a data attribute. Since the Rails tag helpers more or less around the same time introduces the ability to set arbitrary data attributes using the :data option, I guess the decision to nest :confirm inside :data and deprecate the :confirm option was mostly to avoid maintaining support for a separate option in the various helper with the only scope to handle the transformation of a confirm: "foo" into data: { confirm: "foo" }.

    There are some cases where the option is still in place, for example :remote in a form uses data attributes behind the scenes to setup the async submission of a form, however in this case the :remote performs more tasks than a simple "copy the value of this option to a data attribute" therefore it makes sense to keep it as a separate option.

    In the case of :confirm it would be an unnecessary overhead.