2014-02-11 34 views
2

我想爲每個用戶顯示正在進行的會話列表。所以他們可以點擊它並顯示他們想要的對話。由於郵箱中的對話對象沒有ID,因此我無法找到如何建立此鏈接。郵箱:如何顯示特定的會話?

這個ID似乎存儲在通知對象,所以我試過這個選項。

來自談話索引視圖

<%all_conv = current_user.mailbox.conversations%> 
<%all_conv.each do |participant|%> 
    <div class="ligne_conversation"> 
    <ul> 
    <a href="conversations/<%[email protected]_id%>"> 
     <li> 
     <%=image_tag participant.messages.last.sender.avatar.url(:thumb) %> 
     <%=participant.messages.last.sender.name%>     
     <%=participant.messages.last.body%> 
     </li> 
    </a> 
    </ul></div> 

的@conversation_id實例變量是在我的會話控制器定義

def index 
    if current_user.mailbox.conversations.any? 
    notification = Notification.find_by!(params[:id]) 
    @conversation_id = notification.conversation_id 
    end 
end 

它不工作這碼:所有鏈接導致與ID談話= 1.

回答

2

我認爲如果有人點擊一個對話鏈接,它會去你的對話控制器,並尋找def show而不是def index 。因此,你需要有這樣的:

def show 
     @conversation = Conversation.find(params[:id]) 
     respond_to do |format| 
     format.html # show.html.erb 
     format.json { render json: @conversation } 
    end 
    end 

在索引控制器,你需要做的:

def index 
     @conversations = current_user.mailbox.conversations 

最後在你看來,你遍歷@conversations像

@conversations.each do |c| 
    <a href="conversations/<%= c.id %> 

你可能想要查找link_to和url_for使其更加優雅,但上面的內容會起作用。

這裏一個非常簡單的建議爲啓動到你的Rails的冒險:

創建一個新的Rails應用程序:

rails new learncrud 
    cd learncrud 
    rails g scaffold thing name body something:int 
    rake db:migrate 
    rails s 

然後去127.0.0.1:3000/things看看結果

完成後,在您最喜愛的文本編輯器中打開應用程序,並查看腳手架如何創建頁面和控制器操作。也許你已經完成了,也許不是,但是確實有助於快速掌握如何在rails中完成任務。在href中硬編碼控制器名稱肯定不是做事的最佳方式。

+0

感謝您的回答,它工作。我忘了提及我已經在我的show動作中添加了'@conversation = Conversation.find(params [:id])''。我誤解了(也許仍然)如何找到這個特殊的ID。你是對的:這是我的一些教程時間後的第一個應用程序。我會遵循你的建議,我有很多東西要學會它不會受到傷害。 – Ruff9

+0

http://www.railscasts.com是許多知識的絕佳來源,其中許多教程都是免費提供的。瑞恩貝茨的頂級視頻。 –