Rails - display results of index and show actions via ajax

前端 未结 2 560
日久生厌
日久生厌 2021-02-02 03:22

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 displa

2条回答
  •  遥遥无期
    2021-02-02 03:59

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

    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
    

    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
    

    Step 3 - Create _post.html.haml

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

    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) %>");
    

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

提交回复
热议问题