加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails / AJAX部分渲染

发布时间:2020-12-16 21:54:17 所属栏目:百科 来源:网络整理
导读:我做了一个具有项目模型的应用程序.该模型中存储了一些信息,用户可以向项目添加注释(使用注释模型).在项目的展示视图中,我希望用户能够在“info”部分之间切换(包含项目信息和“comment”部分(包含在项目中写的评论),我想使用 AJAX,所以我会有两个按钮:信息
我做了一个具有项目模型的应用程序.该模型中存储了一些信息,用户可以向项目添加注释(使用注释模型).在项目的展示视图中,我希望用户能够在“info”部分之间切换(包含项目信息和“comment”部分(包含在项目中写的评论),我想使用 AJAX,所以我会有两个按钮:信息和评论.

现在我知道如何基于“远程链接”渲染部分,但是我也必须找出哪个链接被点击了.到目前为止,当一个链接被点击时,我可以渲染一个部分:

// In show.html.haml

= link_to("Information",:project,:id => "link_one",:remote => true)
= link_to("Comments",: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’s screencast(有点老,但它得到点)或更多 updated version about nested forms(使用相同的原则).您必须支付更新的版本,但我发现我的RailsCast订阅价值超过$9 /月.另外,这里是 docs的例子.

配置/ 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

观点/评论/ index.js.erb的

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

这使用rails的一个漂亮的东西来查找一个注释部分,并为@comments中的每个注释呈现. j帮助器转义了JavaScript,并且将渲染的部分插入到附加功能中.

观点/评论/ _comment.html.erb

<li> <%= @comment.description %> </li>

所以我们现在已经清除了#holdingDiv并插入了我们的评论.有关信息,可能是这样的:

projects_controller.rb

class ProjectsController < ApplicationController
  def index
    @project = Project.find params[:id]
    respond_to do |format|
      format.html
      format.js
    end
  end
end

意见/项目/ index.js.erb的

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

意见/项目/ _information.html.erb

<h2>
  <%= information.title %>
</h2>
<p>
  <%= infomration.details %>
</p>

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

= link_to("Information",@project,project_comments_url(@project),:remote => true)

我不得不对你的数据结构做些假设.让我知道我在哪里困惑你

此外,我相信我有一些打字错误,对不起.我没有测试这个,刚刚离开了我的头顶.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读