user2239655
user2239655

Reputation: 840

Render partial in rails controller called using ajax

I have rails application where I have part of views as partials and I re-factored couple of views as SPA. I have problem with one functionality. In one place I was rendering partial without calling controller like following:

def create
      school_service.update_preview
      @user = get_user
      @result = prepare_result

      render 'school/result/show', locals: {
        pupil:       @user,
        result:      @result
      }
end

I was calling this method using form. Now I call this from JS using AJAX. Is it possible to render that view in the same way? I wouldn't like to rewrite 'school/result/show' to SPA. Thanks for all answers.

Upvotes: 3

Views: 1050

Answers (1)

Mandeep
Mandeep

Reputation: 9173

Your question says I was calling this method using form. Now I call this using AJAX. Is it possible to render that view in the same way?

Since you are using AJAX i assume you'll have something remote: true in your form something like:

<%= form_for(@user, remote: true) do |f| %>
  # your fields
<% end %>

This will take you to the create action in your controller and you can have a respond_to block in your controller to handle your js format

def create
  @user = get_user
  @result = prepare_result
  respond_to do |format|
    format.js {}
  end
end

This will allow you to have create.js.erb file in your views where you can write your js to render your partial

$(".your_parent_element_class").html("<%=j render partial: "school/result/show",locals:{pupil: @user, result: @result} %>")

For more details checkout working with javascript in rails

Upvotes: 1

Related Questions