Rails / AJAX部分渲染
我创建了一个具有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"))}")
现在,当我点击其中一个链接时,这将呈现_comment.html.haml
部分。 我需要知道的是如何检查单击了哪个链接,然后呈现适当的部分: _info.html.haml
或_comments.html.haml
。
在此先感谢您的帮助!
这样的事情应该有效。 我们将使用嵌套路由。 查看ryan的截屏video ( 有点旧 ,但它得到了重点)或关于嵌套表单的更新版本 (使用相同的原则)。 您将需要支付更新版本,但我发现我的RailsCast订阅价值超过9美元/月。 另外,这里是示例文档 。
config/routes.rb
resources :projects do resources :comments end
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
views/comments/index.js.erb
$('#holderDiv').empty().append(' <%= j render @comments %> ')
这使用了一个很棒的rails来查找部分comment
,并为@comments
每个注释呈现它。 j助手转义javascript并且几乎将渲染的部分插入到append
函数中。
views/comments/_comment.html.erb
<%= @comment.description %>
所以我们现在已经清除了#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
views/project/index.js.erb
$('#holderDiv').empty().append('<%= j render 'information', information: @project.information %>')
views/project/_information.html.erb
<%= information.title %>
<%= infomration.details %>
然后,您的远程链接将是这样的:
= link_to("Information", @project, :remote => true) = link_to("Comments", project_comments_url(@project), :remote => true)
我不得不对你的数据结构做出一些假设。 让我知道我困惑你的地方。
此外,我确信我有一些错别字,抱歉。 我没有测试这个,只是脱了我的头顶。