我可以想到几种方法来做到这一点,但我不确定该选择什么..
我有课 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/