ActiveRecord 根据列表中具有值的关联记录进行条件查找

发布于 2024-11-14 14:17:46 字数 782 浏览 3 评论 0原文

使用以下 Rails 模型:

class Group < ActiveRecord::Base
  has_many    :group_locations, :dependent => :restrict
  has_many    :locations, :through => :group_locations, :dependent => :restrict
end

class Location < ActiveRecord::Base
  has_many        :group_locations, :dependent => :destroy
  has_many        :groups, :through => :group_locations
end

class GroupLocation < ActiveRecord::Base
  belongs_to  :group
  belongs_to  :location
end

我试图查找与字符串“group_list”中包含的多个组中的至少一个相关联的所有位置(例如“1 ,2,3,4,5")。如果它是位置记录中的字段,我将指定“*field in (#{group_list})*”条件。但是,当我想要至少拥有一个其“group_id”在列表中的位置的“group_location”(或者,一个其 group_id 在列表中的“组”)时,我该如何实现我的目标。

我知道如何用纯 SQL 做到这一点,但是如何用 Rails 做到这一点?

With the following Rails models:

class Group < ActiveRecord::Base
  has_many    :group_locations, :dependent => :restrict
  has_many    :locations, :through => :group_locations, :dependent => :restrict
end

class Location < ActiveRecord::Base
  has_many        :group_locations, :dependent => :destroy
  has_many        :groups, :through => :group_locations
end

class GroupLocation < ActiveRecord::Base
  belongs_to  :group
  belongs_to  :location
end

I am trying to Find all of the locations that are associated with at least one of several groups contained in the string "group_list" (e.g. "1,2,3,4,5"). If it was a field from the Location record, I would specify a condition of "*field in (#{group_list})*". But how do I accomplish my goal when I want to have at least one of the location's "group_location" whose "group_id" is in the list (or, alternatively, one "group" whose group_id is in the list).

I know how to do it with pure SQL, but how do you do it with Rails?

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

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

发布评论

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

评论(1

梦境 2024-11-21 14:17:46

@太郎你是对的。首先添加代码

joins(:group_locations).where("group_id in (?)", group_id_array)

然后我继续定义一个范围只是为了使其成为一个漂亮的包:

scope :locations_in_groups, lambda { |grparray| joins(:group_locations).where("group_id in (?)", grparray) }

感谢您的帮助。

@taro You are right. Started by adding the code

joins(:group_locations).where("group_id in (?)", group_id_array)

Then I proceeded to define a scope just to make it a nice package:

scope :locations_in_groups, lambda { |grparray| joins(:group_locations).where("group_id in (?)", grparray) }

Thanks for your help.

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