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"
开发者_StackOverflowI 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.
Try changing joins(:messages) to joins(:sent_messages)
 User.joins(:sent_messages).where(
     {:sent_messages => [:account_id => self.account_id, 
                         :givereceive => "Give"]})
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.
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论