How do I do this query using metawhere and joins?

195 Views Asked by At

I have User.rb:

has_many :sent_messages, :class_name => "Message", :foreign_key => "sent_messageable_id"

Each Message.rb has an account_id and a :givereceive method:

belongs_to :account

I want to create a method for the Account.rb model so that I can show all the Users (uniquetly) who sent a message where the account_id is the same as that account and :givereceive = "Give"

I tried the following:

 User.joins(:sent_messages).where(
     {:sent_messages => [:account_id => self.account_id, 
                         :givereceive => "Give"]})

But I get an error that there is no association with Messages.

Also, this wouldn't remove duplicate instances (for example, the same user created several messages with the same Account).

I am testing it in the console and have the metawhere gem.

Thanks.

2

There are 2 best solutions below

1
On

Try changing joins(:messages) to joins(:sent_messages)

 User.joins(:sent_messages).where(
     {:sent_messages => [:account_id => self.account_id, 
                         :givereceive => "Give"]})
0
On

Add these associations to your models:

class Message < ActiveRecord::Base
  belongs_to :account
  belongs_to :user, :foreign_key => "sent_messageable_id"
end

class Account < ActiveRecord::Base
  has_many :give_messages, :class_name => "Message", :conditions => {:givereceive => "Give"}
  has_many :users, :through => :give_messages
end

Now to get the users you are looking for just call @account.users.