ruby-on-rails - 使用 `where` 语句查找关联计数的最佳语法是什么

标签 ruby-on-rails ruby activerecord

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

我有课 Topic我正在尝试确定它的范围,以便仅在它具有关联对象 Reply 时才返回主题或 topic.replies作为大于 0 的计数。

最糟糕的做法:

@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

我需要将这些选择“附加”到已选择的任何其他内容。所以我的选择不应该将所有其他人排除在这个选择之外。只是说任何 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)

最佳答案

您可以使用一个叫做count cache 的东西,基本上它的作用是向表中添加一个字段并在该字段中存储指定的“关联”总数键入并自动更新。

检查这个旧屏幕/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

希望对你有帮助。

关于ruby-on-rails - 使用 `where` 语句查找关联计数的最佳语法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13848113/

相关文章:

ruby-on-rails - 使用 Carrierwave 保存前修改文件名

javascript - 带有 CKEditor 的 Rails 4 - 插件(codesnipet)不起作用

ruby-on-rails - 将 curl 转换为等效的 ruby

ruby - Rails Fixtures 中的引用用户

php - Yii Model->search() 条件与 MANY_MANY 关系进行比较

mysql - 将关联从一对多更改为多对多

ruby-on-rails - 无法加载此类文件 -- 1.9/bcrypt_ext (LoadError)

ruby-on-rails - 使用 Pow 的欢迎使用 Rails 屏幕上的 SyntaxError

ruby-on-rails - 查找没有 id 的元素进行 Capybara 测试

ruby-on-rails - ActionMailer 实例方法像类方法一样使用