Rails 3 - Update div content with Ajax and jquery (nested resources)

后端 未结 1 484
说谎
说谎 2021-02-04 15:08

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

class Pin < ActiveRecord::Base
    has_many :comments, dependent: :destroy
<
相关标签:
1条回答
  • 2021-02-04 16:12

    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!

    0 讨论(0)
提交回复
热议问题