开发者

ActiveRecord Find with condition based on associated record having a value in a list

With the following Rails models:

class Group < ActiveRecord::Base
  has_many    :group_loca开发者_运维问答tions, :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?


@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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜