导轨 - 指数显示结果,并显示通过ajax行动 [英] Rails - display results of index and show actions via ajax

查看:116
本文介绍了导轨 - 指数显示结果,并显示通过ajax行动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个动作很简单的帖子的资源,索引并显示的。我的模板中包含链接到每个previous后侧边栏。我想补充工具栏的链接来显示其内容(即的作秀行为的结果),通过AJAX

I have a very simple Post resource with two actions, index and show. My template contains a sidebar with links to each previous post. I want the sidebar links to display their content (i.e. the results of the "show" action) via ajax

我知道有很多优秀 <一href="http://stjhimy.com/posts/7-creating-a-100-ajax-crud-using-rails-3-and-unobtrusive-javascript">tuts向您展示如何创建与阿贾克斯,但这次我想用它来显示我的索引中的内容,并显示没有页面referesh行动提交表单

I know there are lots of excellent tuts that show you how to create a form that submits with ajax but this time I want to use it to display the contents of my index and show actions without page referesh

。是否有任何像样的教程在那里,就如何做到这一点提示?

. Are there any decent tutorials out there that give tips on how to do this?

我想我需要创建一个 show.js.erb 的文件,并告诉我的索引行动,以应对JS,但我有点卡住得到任何进一步。我不太知道摆在控制器的表演动作或show.js.erb什么 - 这是一个有点很难想象什么,我需要做的。

I reckon I need to create a show.js.erb file, and tell my index action to respond to js but I'm a little bit stuck getting any further. I don't quite know what to put in controller's show action or show.js.erb - it's a little difficult to visualise what I need to do

PS - 使用Rails 3.0.7,jQuery的-1.5

PS - using rails 3.0.7, jquery-1.5

推荐答案

得到这个工作,它是在最后十分简单。

Got this working, it was very simple in the end.

第1步 - 添加:远程=&GT;真正的在侧边栏链接

Step 1 - add :remote => true to links in sidebar

#application.html.haml
%nav#sidebar
  - for post in @posts
    = link_to post.title, post_path, :remote => true
%div#main
    = yield

第2步 - 告诉你的控制器上显示的行动应对JS

Step 2 - tell your controller to respond to JS on the show action

def show
  @post = Post.find(params[:id])
  @posts=Post.all # needed for sidebar, probably better to use a cell for this
  respond_to do |format|
    format.html # show.html.erb
    format.js # show.js.erb
  end
end

第3步 - 创建_post.html.haml

Step 3 - Create _post.html.haml

# _post.html.haml
%article.post
  = sanitize post.body

第四步 - 创建 show.js.erb 并替换#main分度_post部分内容的HTML(我们创建步骤3)

Step 4 - Create show.js.erb and replace the html in the #main div with the contents of the _post partial (that we created in step 3)

# show.js.erb
$("#main").html("<%= escape_javascript(render @post) %>");

现在所有的内容是通过AJAX过去了,它的正常工作。

Now all the content is passed via ajax and it's working fine.

这篇关于导轨 - 指数显示结果,并显示通过ajax行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆