0

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.

Satchel
  • 16,414
  • 23
  • 106
  • 192

2 Answers2

0

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

 User.joins(:sent_messages).where(
     {:sent_messages => [:account_id => self.account_id, 
                         :givereceive => "Give"]})
Wizard of Ogz
  • 12,543
  • 2
  • 41
  • 43
0

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.

RocketR
  • 3,626
  • 2
  • 25
  • 38