Rails - make link work with ajax

2019-05-12 01:08发布

I have a link that should use ajax to load a partial next to it without reloading the page. Here is the link:

<%= link_to 'test ajax link', profile_form_path , remote: true %>

Here is the controller that the link should go to:

class ProfilesController < ApplicationController
    def profile_form #the action is currently static so there is nothing in the controller
    end
end

And here is the js view that the controller action goes to:
profile_form.js.erb

$('.tab-edit-profile').html("<%= j render 'profile_form_p' %>");

However, it does not work. The browser returns this error:

Template is missing
Missing template profiles/profile_form

Here is the line in the routes file:

get 'profile_form', to: 'profiles#profile_form'

If I change the file name to profile_form.html.erb, the page loads but not using ajax obviously. Can anyone tell me the correct way to use ajax to implement this? Thanks.

2条回答
走好不送
2楼-- · 2019-05-12 01:30

What you need is a partial, for example, _profile.html.erb. The underscore tells Rails this file is rendered as partial. In your profile_form.js.erb you can try.

$('.tab-edit-profile').html("<%= escape_javascript(render 'profile') %>");

That should get you going with static content. For dynamic, setup a @profile instance variable and try.

$('.tab-edit-profile').html("<%= escape_javascript(render @profile) %>");

Be sure to use render json: @profile in your controller response.

查看更多
【Aperson】
3楼-- · 2019-05-12 01:39

From what you posted above, that should work correctly. The only thing I can think of is that you're not including the required javascript libraries and the link_to helper is not actually making an AJAX request.

You indicated that you're using Rails 4 so I'm assuming you're also using the Asset Pipeline. Please ensure that you have the following lines in your app/assets/javascripts/application.js file

//= require jquery
//= require jquery_ujs

and that the javascript is being included in the layout being used by the ProfilesController. Assuming the layout is application.html.erb, ensure that you have

<%= javascript_include_tag "application" %>

in the <head> section of your layout.

查看更多
登录 后发表回答