如何使用metawhere 和连接执行此查询?

发布于 2024-11-18 23:33:25 字数 679 浏览 5 评论 0原文

我有 User.rb:

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

每个 Message.rb 都有一个 account_id 和一个 :givereceive 方法:

belongs_to :account

我想为 Account.rb 模型创建一个方法,以便我可以(唯一地)显示发送了 account_id 消息的所有用户与该帐户相同并且 :givereceive = "Give"

我尝试了以下操作:

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

但我收到一条错误消息,表明与消息没有关联。

此外,这不会删除重复的实例(例如,同一用户使用同一帐户创建了多条消息)。

我正在控制台中测试它并拥有metawhere gem。

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

复古式 2024-11-25 23:33:25

尝试将 joins(:messages) 更改为 joins(:sent_messages)

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

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

 User.joins(:sent_messages).where(
     {:sent_messages => [:account_id => self.account_id, 
                         :givereceive => "Give"]})
红墙和绿瓦 2024-11-25 23:33:25

将这些关联添加到您的模型中:

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

现在只需调用 @account.users 即可获取您正在寻找的用户。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文