Rails: rendering partial data via Ajax

I have a tabbed page and I just want to render different particles through ajax when clicking on the tabs. I have some code, but I don't think this is the most efficient way. I was hoping that if someone could help me with my code that already exists, or if there is a simpler method, I would really appreciate it. Thanks!

HTML tab

<li class='StreamTab StreamTabRecent active'> <%= link_to 'Most Recent', mostrecent_schools_path, :remote => true, :class => 'TabText' %> </li> <div id='ContentBody'> <div id='ajax'></div> <%= render 'users/microposts', :microposts => @microposts %> </div> 

School controller

 class SchoolsController < ApplicationController def mostrecent @school = School.find_by_slug(request.url.gsub('http://localhost:3000/','')).id @microposts = @user.microposts.order('created_at DESC').paginate(:per_page => 3, :page => params[:page]) respond_to do |format| format.html format.js end end end 

Latest js

 $("#ContentBody").html('<%= escape_javascript(render :partial => "users/microposts" )%>'); 

Routes

  resources :schools do collection do get :mostrecent end end 
+6
source share
3 answers

See my answer to the previous post. This will give you an introduction to AJAX in Rails: show the new model form # after the model update is complete #

What you can do is make json in action and pass partial as json.

 def mostrecent @school = School.find_by_slug(request.url.gsub('http://localhost:3000/','')).id @microposts = @user.microposts.order('created_at DESC').paginate(:per_page => 3, :page => params[:page]) respond_to do |format| format.json { render :json => {:success => true, :html => (render_to_string 'users/microposts')} } format.html { } end end 

You can access json in js (e.g. javascript / coffeescript file like mostrecent.js or mostrecent.js.coffee) and replace the current element.

 $('.TabText').live 'ajax:success', (event,data) -> $('#ContentBody').html(data.html) if(data.success == true) 
+10
source

Prasvin's answer is in place. Returning and executing JS may seem simple, but it makes debugging more unpleasant - how do you set a breakpoint in JS that was returned via AJAX? Instead, you should include all of your JS in the page and only send the data back.

+2
source

I use rails 4.2 and @prasvin the answer pointed me in the right direction, but when I used

 format.json { render :json => {:success => true, :html => (render_to_string 'instruments')} } 

I get the error "The template is missing ... tools ..."

After some reading, I found this comment rails render_to_string giving partial view errors . @marcel noted that you need to indicate that the file is partial, partial: "tools" as shown below:

 format.json { render :json => {:success => true, :html => (render_to_string partial: 'instruments')} } 
0
source

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


All Articles