【问题标题】:Use named_scope to find number of associated rows (Ruby on Rails + Searchlogic question)使用 named_scope 查找关联行数(Ruby on Rails + Searchlogic 问题)
【发布时间】:2010-05-11 17:45:00
【问题描述】:
假设我有:
class ForumTopic < ActiveRecord::Base
has_many :forum_posts
named_scope :number_of_posts, ??????
end
class ForumPost < ActiveRecord::Base
belongs_to :forum_topic
end
我应该放什么??????允许搜索逻辑查询,例如:
ForumTopic.descend_by_number_of_posts
任何帮助将不胜感激!
【问题讨论】:
标签:
ruby-on-rails
named-scope
searchlogic
【解决方案1】:
你想按帖子数量排序,对吗?
我认为如果你使用:counter_cache 会更容易,因为如果你这样做,你可以像这样订购:
class ForumTopic < ActiveRecord::Base
has_many :forum_posts
named_scope :by_number_of_posts, :order => "forum_posts_count"
end
# controller
ForumTopic.by_number_of_posts.all
要使用:counter_cache,您需要更改关联
class ForumPost < ActiveRecord::Base
belongs_to :forum_topic, :counter_cache => true
end
并在forum_topics 表上创建一个forum_posts_count 列。
我相信就是这样。