Rails 3 - Update div content with Ajax and jquery

2020-05-24 16:50发布

问题:

I've two simple models, Pin and Comment, Comments belongs to Pin:

class Pin < ActiveRecord::Base
    has_many :comments, dependent: :destroy

and

class Comment < ActiveRecord::Base
    belongs_to :pin

In the index action of Pin I've basically a list of all the pins + a div. This div must show all the comments when user select a pin.

Concept is quite simple, but I can't figure out how to achieved it. I've found many subjects related, but I always lost myself in the differences with my problem.

Some precise questions:

  • How to do this ajax load? (with jquery)
  • Do I need to use partials or use index view of comments?

回答1:

I'm going to use a link for the user to select a Pin but you get the idea:

#:remote => true allows ajax stuffz.
<%= link_to 'show comments', pin_comments_path(@pin), :remote=> true %>

In the comments_controller.rb (i'm using the index action here, but tweak to your needs)

def index 
  @pin = Pin.find(params[:pin_id])
  @comments = @pin.comments.all

  respond_to do |format|
    format.js { render :pin_comments }
  end
end

In this case the controller will look to render pin_comments.js.erb, which will interact with your comments div.

//pin_comments.js.erb
$("#comments_div").html("<%= j(render('show_comments', :comments=> @comments)) %>");

View partial template to show comments

#_show_comments.html.erb
<div id="comments_div">
    <% comments.each do |c| %> 
        <p>
           <h1><%= c.title %></h1>
           <h6>by <%= c.author %> </h6>
           <%= c.content %>
        </p>
    <% end %>
</div>

Hope that helps!