开发者

How do I do this query using metawhere and joins?

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"

开发者_StackOverflow

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜