How to use the link_to helper to open a popup?

橙三吉。 提交于 2019-11-28 21:38:19

My first stab at this problem would probably look something like this. It assumes you're using rails 3, jQuery and jquery-rails. If you're not, this approach definitely won't work. This exact code isn't tested, so your mileage may vary. I'm just trying to give you an idea on how you might want to think about the problem. If you'd like me to elaborate on how this works, or have questions, let me know and I'll do my best to explain.

Turn your link_to into an ajax post:

<%= link_to "Create a new company", new_company_path, :remote => true, :method => :post %>

In your controller, respond with a javascript template:

def create
    @company = Company.new(params[:company])
    respond_to do |format|
       if @company.save
          format.js
       else
          format.js { render 'error' }
       end
    end
end

In views/companies/create.js.erb, execute the JS to open the new window.

window.open (<%= company_url(@company) %>, "mywindow","width=600,height=600");

And that should more or less do it, I think. I've had a few beers, so proceed with caution.

Add this to your application.js.

$('a[data-popup]').on('click', function(e) { window.open($(this).attr('href')); e.preventDefault(); });

In the view, use something like:

= link_to( 'Create a new company', new_company_path, 'data-popup' => true )
Viktor Trón
<%= link_to 'Create a new company',
         new_company_path, 
        :onclick=>"window.open(this.href,'create_company', 'height=600, width=600');return false;" 
%>

If your goal is just to open the link in a new window and you don't care about managing the dimensions/toolbar/etc, you can also use good old HTML:

<%= link_to 'Create a new company', new_company_path, :target => '_blank' %>

This is the quick and dirty solution

<%= link_to 'Create a new company',
             '#', :onclick => "javascript:window.open(new_company_path,'popup','width=600,height=600');" %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!