我新來的鐵軌。我想爲我的Rails應用程序添加一個搜索功能。用戶可以搜索他與其他用戶進行的對話。在那個搜索中,他可以鍵入消息的關鍵字或他聊天的用戶名。可有一個人指導我該...軌道上紅寶石對話的搜索功能
conversation.rb是,
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 :involving, -> (user) do
where("conversations.sender_id = ? OR conversations.recipient_id = ?", user.id, user.id)
end
scope :between, -> (sender_id, recipient_id) do
where("(conversations.sender_id = ? AND conversations.recipient_id = ?) OR (conversations.sender_id = ? AND conversations.recipient_id = ?)",
sender_id, recipient_id, recipient_id, sender_id)
end
end
message.rb是,
class Message < ActiveRecord::Base
belongs_to :conversation
belongs_to :user
validates_presence_of :content, :conversation_id, :user_id
def message_time
created_at.strftime("%v")
end
end
conversations_controller.rb是,
class ConversationsController < ApplicationController
before_action :authenticate_user!
def index
@users = User.all
@conversations = Conversation.involving(current_user)
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
private
def conversation_params
params.permit(:sender_id, :recipient_id)
end
end
messages_controller.rb是,
class MessagesController < ApplicationController
before_action :authenticate_user!
before_action :set_conversation
def index
if current_user == @conversation.sender || current_user == @conversation.recipient
@other = current_user == @conversation.sender ? @conversation.recipient : @conversation.sender
@messages = @conversation.messages.order("created_at DESC")
else
redirect_to conversations_path, alert: "You don't have permission to view this."
end
end
def create
@message = @conversation.messages.new(message_params)
@messages = @conversation.messages.order("created_at DESC")
if @message.save
respond_to do |format|
format.js
end
end
end
private
def set_conversation
@conversation = Conversation.find(params[:conversation_id])
end
def message_params
params.require(:message).permit(:content, :user_id)
end
end
有人可以指導我編寫搜索功能並查看搜索結果。我嘗試過兩種不同的類型,但沒有奏效。在此先感謝
添加後,當我搜索一條消息,它顯示所有的對話......顯示的網址是[http:// localhost:3000/conversations?utf8 =%E2%9C%93&search = hello]但它顯示相同的會話頁面 – MSK