Alexandr Borovkov
Alexandr Borovkov

Reputation: 65

Rails - How to search through has many relation

I have 3 models - User, Conversation and UserConversation

class Conversation < ApplicationRecord
  has_many :messages,  -> { order 'created_at' }, dependent: :destroy
  has_many :user_conversations, dependent: :destroy
  #if conversation is destroyed all messages and subscriptions will also be  destroyed
  has_many :users, through: :user_conversations
end
class User < ApplicationRecord
    has_many :sent_messages, 
           class_name: 'Message', 
           foreign_key: 'sender_id' 
    has_many :messages, foreign_key: 'recipient_id'

    has_many :user_conversations, dependent: :destroy
    has_many :conversations, through: :user_conversations

end
class UserConversation < ApplicationRecord
  belongs_to :user
  belongs_to :conversation

  validates_presence_of :user_id, scope: :conversation_id
end

I want to search through conversations of current user and find only conversations where other users name like some value.

conversations = @current_user.conversations
conversations = conversations.users.where("name ILIKE ?", "%#{params[:search]}%")

But it doesn't work. How to implement it?

Upvotes: 3

Views: 93

Answers (2)

user11963900
user11963900

Reputation:

I'm not sure if your model Conversation it is an abstraction or it really pretend to be a chat but if you want to find all conversation from the current_user with another user you need your Conversation model to have relations with both users, but the way your relations works are confusing, try with:

class User < ApplicationRecord
  # all your previous code

  def find_conversations_by(user_name)
    self.conversations.joins(:user).where("user.name ILIKE ?", "%#{user_name}%") 
  end
end

And now, wherever you want to use it write this:

current_user.find_conversations_by(a_proof_query_injection_string)

By the way, I suggest you to look for another approach.

Upvotes: 1

demir
demir

Reputation: 4709

This should be work:

Conversation.joins(:users)
            .where(users: { id: @current_user })
            .where("users.name ILIKE ?", "%#{params[:search]}%")

Upvotes: 0

Related Questions