我正在爲我的應用程序開發一個基本的私人消息系統。我以Medium上的this tutorial開始。Rails返回所有對話記錄,而不僅僅是相關的記錄。
雖然我發現了一個問題。它返回所有對話,而不僅僅是當前用戶實際參與的對話。視圖只顯示你正在進入的對話,但所有記錄都在那裏。顯然,如果你的用戶不止一個,那就太糟糕了。
我調整了控制器到我認爲是解決方案,但我仍然得到所有記錄,所以我認爲這個問題是在模型中。
對話控制器
class ConversationsController < ApplicationController
before_action :authenticate_user!
before_action :set_conversation, only: [:destroy]
def index
@user = current_user
@conversations = Conversation.where(:sender_id == @user.id || :recipient_id == @user.id)
end
def create
if Conversation.between(params[:sender_id],params[:recipient_id])
.present?
@conversation = Conversation.between(params[:sender_id],
params[:recipient_id]).first
else
@conversation = Conversation.create!(conversation_params)
end
redirect_to conversation_messages_path(@conversation)
end
會話模型
class Conversation < ActiveRecord::Base
belongs_to :sender, :foreign_key => :sender_id, class_name: 'User'
belongs_to :recipient, :foreign_key => :recipient_id, class_name: 'User'
has_many :messages, dependent: :destroy
validates_uniqueness_of :sender_id, :scope => :recipient_id
scope :between, -> (sender_id,recipient_id) do
where(sender_id: [sender_id,recipient_id], recipient_id: [sender_id,recipient_id])
end
def unread_message_nr_for(user_id)
messages.where('messages.read = ?', false).where('messages.user_id != ?', user_id).count
end
end
會話視圖
<div class="ibox-content no-side-borders">
<% @conversations.each do |conversation| %>
<div class="conversation-member">
<% if conversation.sender_id == current_user.id || conversation.recipient_id == current_user.id %>
<% if conversation.sender_id == current_user.id %>
<% recipient = User.find(conversation.recipient_id) %>
<% else %>
<% recipient = User.find(conversation.sender_id) %>
<% end %>
<span class="<%= 'current-conversation' if (params['conversation_id'].to_i == conversation.id) %>">
<% if recipient.avatar.present? %>
<%= image_tag(recipient.avatar_url(:navigation), class: "img-circle m-r-xs") %>
<% end %>
<%= link_to recipient.first_name + " " + recipient.last_name, conversation_messages_path(conversation)%>
</span>
<% if conversation.unread_message_nr_for(current_user.id) > 0 %>
<span class="badge-inline">
<%= conversation.unread_message_nr_for(current_user.id) %>
</span>
<% end %>
<% end %>
</div>
<% end %>
</div>
個對話模式
create_table "conversations", force: :cascade do |t|
t.integer "sender_id"
t.integer "recipient_id"
t.datetime "created_at"
t.datetime "updated_at"
end
我怎樣才能得到只有在當前用戶是SENDER_ID或recipient_id的談話?
相反的PARAMS [:SENDER_ID],則params [:recipient_id],不應該說,它是conversation_params [:SENDER_ID]和conversation_params [:recipient_id]? –