Rails - 通过ajax显示索引和显示操作的结果

ste*_*och 8 ajax ruby-on-rails

我有一个非常简单的Post资源,有两个动作,索引和显示.我的模板包含一个侧栏,其中包含指向每个帖子的链接.我希望侧边栏链接通过ajax 显示其内容(即"show"操作的结果)

我知道有很多优秀的 tuts向你展示如何创建一个用ajax提交的表单,但这次我想用它来显示我的索引的内容并显示没有页面引用的动作

.是否有任何体面的教程可以提供有关如何执行此操作的提示?

我想我需要创建一个show.js.erb文件,并告诉我的索引操作响应js但我有点陷入困境.我不知道在控制器的show动作或show.js.erb中放什么 - 想象我需要做什么有点困难

PS - 使用rails 3.0.7,jquery-1.5

ste*_*och 10

得到了这个工作,最终它非常简单.

第1步 - 添加:remote => true到侧栏中的链接

#application.html.haml
%nav#sidebar
  - for post in @posts
    = link_to post.title, post_path, :remote => true
%div#main
    = yield
Run Code Online (Sandbox Code Playgroud)

第2步 - 告诉你的控制器在show动作上回应JS

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

第3步 - 创建_post.html.haml

# _post.html.haml
%article.post
  = sanitize post.body
Run Code Online (Sandbox Code Playgroud)

第4步 - 创建show.js.erb并将#main div中的html替换为_post partial(我们在步骤3中创建)的内容

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

现在所有内容都通过ajax传递,并且工作正常.

  • 有没有办法使用网址来操纵@post显示? (2认同)