Rails/AJAX部分渲染

Ste*_*gen 9 ajax ruby-on-rails

我创建了一个有project模型的应用程序.模型中存储了一些信息,用户可以向project(使用comment模型)添加注释.在项目的show视图中,我希望用户能够在"info"部分(包含项目信息和"注释"部分(包含项目中写的注释))之间切换.我想使用AJAX.所以我将有两个按钮:信息和评论.

现在我知道如何基于"远程链接"呈现部分,但我还必须找出点击了哪个链接.到目前为止,我可以在点击一个链接时渲染一个部分,如下所示:

// In show.html.haml

= link_to("Information", :project, :id => "link_one", :remote => true)
= link_to("Comments", :project, :id => "link_two", :remote => true)

#partial_window


// In show.js.haml
$("#partial_window").html("#{j(render("comments"))}")
Run Code Online (Sandbox Code Playgroud)

现在,_comment.html.haml当我点击其中一个链接时,这会呈现部分.我需要知道的是如何检查单击了哪个链接,然后呈现适当的部分:_info.html.haml_comments.html.haml.

在此先感谢您的帮助!

Tyl*_*itt 23

这样的事情应该有效.我们将使用嵌套路由.查看ryan的截屏视频(有点旧,但它得到了重点)或关于嵌套表单的更新版本(使用相同的原理).您将需要支付更新版本,但我发现我的RailsCast订阅价值超过9美元/月.另外,这里是示例文档.

config/routes.rb

resources :projects do
  resources :comments
end
Run Code Online (Sandbox Code Playgroud)

comments_controller.rb

class CommentsController < ApplicationController
  def index
    project = Project.find params[:project_id]
    @comments = project.comments
    respond_to do |format|
     format.html #responds with default html file
     format.js #this will be the javascript file we respond with
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

views/comments/index.js.erb

$('#holderDiv').empty().append('<ul> <%= j render @comments %> </li>')
Run Code Online (Sandbox Code Playgroud)

这使用一个漂亮的rails来寻找一个comment部分并为每个评论呈现它@comments.j助手转义javascript并且几乎将渲染的部分插入到append函数中.

views/comments/_comment.html.erb

 <li> <%= @comment.description %> </li>
Run Code Online (Sandbox Code Playgroud)

所以我们现在已经清除#holdingDiv并插入了我们的评论.对于information,可能是这样的:

projects_controller.rb

class ProjectsController < ApplicationController
  def index
    @project = Project.find params[:id]
    respond_to do |format|
      format.html
      format.js
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

views/project/index.js.erb

 $('#holderDiv').empty().append('<%= j render 'information', information: @project.information %>')
Run Code Online (Sandbox Code Playgroud)

views/project/_information.html.erb

<h2>
  <%= information.title %>
</h2>
<p>
  <%= infomration.details %>
</p>
Run Code Online (Sandbox Code Playgroud)

然后,您的远程链接将是这样的:

= link_to("Information", @project, :remote => true)
= link_to("Comments", project_comments_url(@project), :remote => true)
Run Code Online (Sandbox Code Playgroud)

我不得不对你的数据结构做出一些假设.让我知道我困惑你的地方.

此外,我确信我有一些错别字,抱歉.我没有测试过这个,只是脱了我的头顶.