【发布时间】:2011-09-11 09:22:58
【问题描述】:
使用以下 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_location”,其“group_id”在列表中(或者,一个“组”,其 group_id 在列表中)时,我该如何实现我的目标。
我知道如何用纯 SQL 做到这一点,但你如何用 Rails 做到这一点?
【问题讨论】:
-
如果您知道如何在纯 SQL 上执行此操作,您就知道如何使用活动记录执行此操作。只需使用 Location::find 并按组件拆分查询 - :joins、:group、:have 等。
-
@taro 你是对的。首先添加代码 joins(:group_locations).where("group_id in (?)", group_id_array)。然后我开始定义一个范围,只是为了使它成为一个不错的包: scope :locations_in_groups, lambda { |grparray| joins(:group_locations).where("group_id in (?)", grparray) }.感谢您的帮助。
标签: sql activerecord has-many-through