Rails: link_to with remote true and opening it in a new tab or window

I have a link that, when clicked, calls an AJAX call. This AJAX call will lead to a modality.

= link_to edit_evaluation_path(evaluation), remote: true

However, when I try to open a new tab from a link (for example, by clicking on it with the middle mouse button), I get an error ActionController::UnknownFormat: ActionController::UnknownFormatbecause the action does not expect a response using the html format. Here is the code respond_tofrom the corresponding action:

respond_to do |format|
  format.js
end

How can I prevent a user from opening a link in another tab or window? Am I obligated to change link_toto button_to? Thank!

+4
source share
2 answers

I only created a Javascript solution for this problem that I was working on today.

$.each($("a[data-remote='true']"), function(i, val) {
  $(val).data("url", $(val).attr("href")).attr("href", "javascript:void(0);")
});

$.rails.href = function(el) {
  var $el = $(el);
  return $el.data('url') || $el.data('href') || $el.attr('href');
}
Hide result

+1

. :

jquery-ujs, URL , . , data, href.

$.rails.href = function(el) {
    var $el = $(el);
    return $el.attr('data-url') || $el.attr('data-href') || $el.attr('href');
}

. , , URL- data, href.

  def pseudo_link_to(name = nil, options = nil, html_options = nil, &block)
    html_options, options, name = options, name, block if block_given?
    options ||= {}

    html_options = convert_options_to_data_attributes(options, html_options)

    url = url_for(options)
    html_options["data-href".freeze] ||= url
    html_options['href'] = 'javascript:void(0)'
    content_tag("a".freeze, name || url, html_options, &block)
  end

, href javascript:void(0), javascript no-op.

, , pseudo_link_to link_to.

0

Source: https://habr.com/ru/post/1544628/


All Articles