【问题标题】:Selecting records based on association count (join?)根据关联计数选择记录(加入?)
【发布时间】:2012-01-01 19:31:11
【问题描述】:

三种型号:

class Customer < ActiveRecord::Base
  has_many :visits
end

class Visit < ActiveRecord::Base
  belongs_to :customer
  has_many :messages
end

class Message < ActiveRecord::Base
  belong_to :visit
end

现在我想返回他们有消息的所有客户访问。所以在伪代码中是这样的:

@customer = Customer.find(:id)
@customer.visits.where(visit has messages)

我该如何做这样的事情?

【问题讨论】:

    标签: sql ruby-on-rails activerecord ruby-on-rails-3.1 associations


    【解决方案1】:

    做一个inner join:(推荐):

    # returns a customer's visits that have at least one message
    @customer.visits.joins(:messages)
    

    确保处理重复项

    @customer.visits.joins(:messages).(“distinct(categories.id, categories.name)”)
    

    由于可能存在性能问题,另一种选择是使用SQL EXISTS 子句:

    @customer.visits.where("EXISTS (SELECT messages.id FROM messages WHERE messages.visit_id == visits.id)")
    

    SQL IN:

    @customer.visits.where("visits.id IN (SELECT messages.visit_id FROM messages)")
    

    http://guides.rubyonrails.org/active_record_querying.html#using-array-hash-of-named-associations

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-01
      • 2019-11-03
      • 2012-11-03
      • 2012-06-21
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      相关资源
      最近更新 更多