2010-09-11 48 views
2

我希望用戶能夠評論提交內容。在每個提交下面,我希望有一個鏈接,說:「評論(2)」...當你點擊這個鏈接它動態加載評論,以及一個簡單的形式來添加一個新的評論。當用戶提交新評論時,我希望它在列表底部異步加載。Rails Ajax隱藏/顯示使用RJS的切換鏈接

我怎麼會有現在的工作如下:

// index.html.erb 

<p class="comments_view_toggle"> 
    <%= link_to_remote("▼ view comments (#{answer.comments.count})", :controller => "comments", :action => "show", :submission => submission, :update => "comment") %> 
</p> 

// comments_controller.rb 

    def show 
    @submission = Submission.find(params[:submission]) 
    respond_to do |format| 
     format.html { redirect_to root_url } 
     format.js 
    end 
    end 

// show.rjs 

page.insert_html :bottom, :comment, :partial => 'show', :locals => { :submission => @submission } 

// _show.html.erb 

    <ul id="comment_list"> 
     <%= render :partial => 'comments/comment', :collection => submission.comments %> 
    </ul> 

    <div class="clear"></div> 

     <% form_remote_for Comment.new do |f| %> 
      <%= hidden_field_tag(:submission_id, answer.id)%> 
      <%= hidden_field_tag(:user_id, current_user.id)%> 
      <%= f.text_area :message %> 
      <%= f.submit "comment", :disable_with => 'commenting...' %> 
     <% end %> 

我還沒有上切換功能,但(隱藏)的第二部分工作,因爲每當我點擊鏈接它重新加載整個頁面在鏈接的下面,而不是僅僅運行部分,我不知道爲什麼。它似乎沒有正確傳遞參數。我是否全部錯了?你能爲我指出正確的方向嗎?

回答

1

你可以通過使用原型ajax庫來實現,默認情況下它附帶rails。否則,你可能想用jQuery做,

這裏做的一種方式這

說你有下面的HTML頁面

<div id="submission"> 
    // your submission details goes here 
</div> 
//here you will have your link says "comments" 
<div id="comments"> 

</div> 

一旦你點擊「評論」的鏈接,你可以使用link_to_remote加載評論格內的所有意見

例如: link_to_remote 「查看評論」:更新=> 「意見」, :URL => {:動作=> 「意見」:ID => submission.id}

讓你的控制器看起來就像

class SubmissionsController < ApplicationController 
    #your other code goes here 

    def list 
    #code to generate the comments list 
    render :partial => 'comments_list', :object => @comments 
    end 
end 

,你可以有一個局部的列表意見「_comments_list」

+0

應該不會是「高清意見」而不是「DEF名單」? – Magne 2011-04-14 20:38:37