我一直试图让我的对话只能由发送者和接收者查看。任何帮助或方向指示将不胜感激。
对话控制器
class ConversationsController < ApplicationController
def index
@conversations = Conversation.all
#@conversation = current_user.conversation.from_id + @user.conversation.to_id
#@conversations = current_user.messages.find(params[:id])
#@conversations = current_user && @user != current_user
#@conversations = Conversation.find(current_user).last
#@conversations = from.id + to.id
end
会话模型
class Conversation < ActiveRecord::Base
validates :to_id, :from_id, presence: true
belongs_to :to, class_name: "User"
belongs_to :from, class_name: "User"
has_many :messages, dependent: :destroy, inverse_of: :conversation
def self.exist_with?(user, current_user)
if Conversation.where(from_id: user.id ,to_id: current_user.id).blank? &&
Conversation.where(from_id: current_user.id, to_id: user.id).blank?
return false
else
return true
end
end
def self.find_conversation(user, current_user)
conversation = Conversation.where(from_id: user.id ,to_id: current_user.id) +
Conversation.where(from_id: current_user.id, to_id: user.id)
conversation.first
end
end
对话Index.html.erb
<h1 class="message"> Messages </h1>
<ul>
<% @conversations.reverse.each do |conversation| %>
<li class="cmessages">
<%= image_tag conversation.to.avatar.url(:thumb), :class => "username-picture" %>
<%= link_to conversation.to.user_name, "/conversations/#{ conversation.id }", :class => "username" %>
<%= time_ago_in_words(conversation.created_at) %> ago
</li>
<% end %>
对话架构
create_table "conversations", force: true do |t|
t.integer "to_id"
t.integer "from_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "user_id"
end
如果缺少某些内容,请通知我,我将包含可能缺少的任何文件信息以解决此问题。再次感谢大家的帮助,并为我的问题指出正确的方向。祝你有美好的一天。
答案 0 :(得分:1)
class ConversationsController < ApplicationController
def index
@conversations = Conversation.where("from_id = :user OR to_id = :user", user: current_user.id)
end
为避免将模型逻辑填充到控制器中,请在模型中创建方法或范围
class Conversation < ActiveRecord::Base
def self.accessible_by(user)
where("from_id = :user OR to_id = :user", user: user.id)
end
end
并在控制器中重复使用
class ConversationsController < ApplicationController
def index
@conversations = Conversation.accessible_by(current_user)
end
还要注意以下查询
where("from_id = :user OR to_id = :user", user: user.id)
这只是
的捷径where("from_id = ? OR to_id = ?", user.id, user.id)