使用“where”语句查找关联计数的最佳语法是什么



我可以想到几种方法来做到这一点,但我不确定该选择什么。

我有类Topic,我正在尝试限定它的范围,以便仅当它具有关联的对象Replytopic.replies为大于 0 的计数时,我才返回 Topics。

最糟糕的方法:

@topics.select{ | topic | topic.replies > 0 && topic.title == "Conversation" }

理想情况下,我想使用where范围。

  scope = current_user.topics
  scope = scope.joins 'left outer join users on topics.registration_id = registration_members.registration_id'
  # scope = .. here I want to exclude any of these topics that have both the title "Conversations" and replies that are not greater than 0

我需要将这些选择"追加"到其他已选择的内容中。因此,我的选择不应将所有其他选择排除在此选择之外。这只是说,任何回复少于 1 且也称为"对话"的Topic都应从最终返回中排除。

有什么想法吗?

更新

有点半散列的想法:

items_table = Arel::Table.new(scope)
unstarted_conversations = scope.select{|a| a.title == "Conversation" && a.replies.count > 0}.map(&:id)
scope.where(items_table[:id].not_in unstarted_conversations)

您可以使用称为计数缓存的东西,基本上它的作用是将一个字段添加到表中,并在该字段中存储指定类型的"关联"总数并自动更新。

查看此旧屏幕/ASCII 演员表:http://railscasts.com/episodes/23-counter-cache-column?view=asciicast

这是更新的内容:http://hiteshrawal.blogspot.com/2011/12/rails-counter-cache.html

在您的情况下如下:

# migration
class AddCounterCacheToTopìc < ActiveRecord::Migration
  def self.up
    add_column :topics, :replies_count, :integer, :default => 0
  end
  def self.down
    remove_column :topics, :replies_count
  end
end
# model
class Replay < ActiveRecord::Base
  belongs_to :topic, :counter_cache => true
end

希望对您有所帮助。

最新更新