Rails 3 - 使用Ajax和jquery(嵌套资源)更新div内容

Alr*_*lon 8 ajax jquery nested ruby-on-rails ruby-on-rails-3

我有两个简单的模型,Pin和Comment,评论属于Pin:

class Pin < ActiveRecord::Base
    has_many :comments, dependent: :destroy
Run Code Online (Sandbox Code Playgroud)

class Comment < ActiveRecord::Base
    belongs_to :pin
Run Code Online (Sandbox Code Playgroud)

在Pin I的索引动作中,基本上是所有引脚+ div的列表.当用户选择一个引脚时,该div必须显示所有注释.

概念很简单,但我无法弄清楚如何实现它.我发现很多相关的主题,但我总是迷失在与我的问题的差异.

一些确切的问题:

  • 怎么做这个ajax加载?(用jquery)
  • 我是否需要使用partials或使用注释的索引视图?

tw *_*all 15

我将使用一个链接供用户选择Pin,但你明白了:

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

在comments_controller.rb中(我在这里使用索引操作,但根据您的需要调整)

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

  respond_to do |format|
    format.js { render :pin_comments }
  end
end
Run Code Online (Sandbox Code Playgroud)

在这种情况下,控制器将查看渲染pin_comments.js.erb,它将与您的注释div进行交互.

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

查看部分模板以显示评论

#_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>
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!