1

是否可以在两个模型没有直接关联的情况下进行以下查询:

Event.where(community_id: 1)

这是三个模型:

class Community < ActiveRecord::Base
  has_many :organizers
end

class Organizer < ActiveRecord::Base
  belongs_to :community
  has_many  :events
end

class Event < ActiveRecord::Base
  belongs_to :organizer
end

我最接近的方法是将“委托”与以下内容一起使用,这适用于 event.communities 但不适用于 where 查询:

delegate :community, :to => :organizer, :allow_nil => true
4

1 回答 1

3

你可以这样做:

Event.joins(organizer: :community).where("communities.id = ?", 1)

或者:

Event.joins(:organizer).where("organizers.community_id = ?", 1)
于 2013-05-19T14:34:42.000 回答