Julio Ahuactzin
Julio Ahuactzin

Reputation: 91

Render to partial by Ajax in Rails App

I have almost done! but I have an issue, in my Controller file have this:

def show
   @user = User.find(params[:id])
   @posts = @user.posts.paginate(page: params[:page])
end

Then I have this piece of code in my file show.html.erb:

<div class="span8">
   <%= render 'follow_form' if signed_in? %>
 <% if @user.posts.any? %>
    <h3>Microposts (<%= @user.posts.count %>)</h3>
    <div id='posts'>
      <div class='page'>
     <ol class="microposts">
        <%= render @posts %>
     </ol>
  </div>
</div>
   <% end %>
 </div>

At the bottom of this file, I have a Javascript code that I have taken from the tutorial: https://github.com/amatsuda/kaminari/wiki/How-To:-Create-Infinite-Scrolling-with-jQuery

In the same folder I have the file index.js.erb with:

$("#articles").append("<div class='page'><%= escape_javascript(render(@users)) %></div>");
$("#posts").append("<div class='page'><%= escape_javascript(render(@posts)) %></div>");

In a partial _posts.html.erb have this:

<div class='article'>
  <%= image_tag(user.picture_url, :width => 50) %>
  <%= link_to user.name, user %>
  <% if current_user.admin? && !current_user?(user) %>
    | <%= link_to "delete", user, method: :delete,
                              data: { confirm: "You sure?" } %>
  <% end %>
</div>

The first one already works in my file index.html.erb, the problem is with the second piece of code, when I try to render the partial at @post, It brings the follow log:

**
'nil' is not an ActiveModel-compatible object that returns a valid partial path.
Extracted source (around line #2):
1: $("#articles").append("<div class='page'><%= escape_javascript(render(@users)) %></div>");
2: $("#posts").append("<div class='page'><%= escape_javascript(render(@posts)) %></div>");
**

How can I render that partial?

Thanks a lot :D

Upvotes: 1

Views: 400

Answers (2)

Samiron
Samiron

Reputation: 5317

Based on your In script I'm calling to /users?page=, and I was wondering that It may calls the line, you must make sure that your controller is populating the @posts variable if your view is using this. Can you show the controller method users?

Upvotes: 0

George
George

Reputation: 668

I usually use the .js.erb template to render the partial into a var then set it on the page using JS. Be sure to escape_javascript the template content otherwise you will get JS errors.

<% template_html = render :partial => '_feed_item.html.erb' %>
<%="$('div#content').html('#{escape_javascript(template_html)}</div>');" %>

I think the above should work in erb. I use HAML so mine looks like:

-template_html = render :partial => 'partial_template'
!="$('div#content').html('#{escape_javascript(template_html)');"

Cheers.

Upvotes: 1

Related Questions