ruby on rails - Querying model by attribute of HABTM association -


i have habtm association between 2 models, user , conversation. want able query logged-in user's conversations (current_user.conversations), passing user's id, , have return conversation shared both users, if 1 exists. (an additional perk have query create 1 if 1 doesn't exist.)

the associations working fine, can access associated objects through instance variables @user.conversations , @conversation.users, go long way , loop through each conversation object , search user associations in each of them... there must efficient way construct query. able current_user.conversations.where(conversation.users.exists?(id: @user_id)) or conversation.find(users: {id: @user_id , current_user.id}).

i imagine there obvious answer this, , i've been searching around here similar questions haven't found any. after looking through rails api docs, imagine solution i'm looking involves .includes() in way, can't working.

any advice? thanks.

suppose have 2 users @sender , @receiver, , there 1 (or perhaps more) conversation between them. 1 possible way query shared conversations using merge function in activerecord. merge select intersection of conversations between between them:

@shared_conversations = @sender.conversations.merge(@receiver.conversations) 

note result collection, not individual conversation. in sql translate inner join.

if wanted amend query create conversation if didn't exist, can use first_or_create. name implies, first_or_create returns first item in collection. if collection empty, create new object. can pass block further control on newly created object:

@shared_conversations = @sender.conversations.merge(@receiver.conversations).first_or_create |conversation|   conversation.title = "#{@sender.first_name}'s conversation" end 

you can find more details on merge in rails docs: http://apidock.com/rails/activerecord/spawnmethods/merge.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -