【发布时间】:2011-12-22 09:20:35
【问题描述】:
在这样的域中:
class User
has_many :posts
has_many :topics, :through => :posts
end
class Post
belongs_to :user
belongs_to :topic
end
class Topic
has_many :posts
end
我可以通过user.topic_ids 读取所有主题ID,但我看不到将过滤条件应用于此方法的方法,因为它返回Array 而不是ActiveRecord::Relation。
问题是,给定一个用户和一组 现有 主题,标记用户发布的主题。我目前正在做这样的事情:
def mark_topics_with_post(user, topics)
# only returns the ids of the topics for which this user has a post
topic_ids = user.topic_ids
topics.each {|t| t[:has_post]=topic_ids.include(t.id)}
end
但是无论输入集如何,这都会加载所有主题 ID。理想情况下,我想做类似的事情
def mark_topics_with_post(user, topics)
# only returns the topics where user has a post within the subset of interest
topic_ids = user.topic_ids.where(:id=>topics.map(&:id))
topics.each {|t| t[:has_post]=topic_ids.include(t.id)}
end
但我唯一能具体做的就是
def mark_topics_with_post(user, topics)
# needlessly create Post objects only to unwrap them later
topic_ids = user.posts.where(:topic_id=>topics.map(&:id)).select(:topic_id).map(&:topic_id)
topics.each {|t| t[:has_post]=topic_ids.include(t.id)}
end
有没有更好的方法?
是否可以在关联或范围上有类似 select_values 的东西?
FWIW,我正在使用 rails 3.0.x,但我也对 3.1 感到好奇。
我为什么要这样做?
基本上,我有一个半复杂搜索的结果页面(仅基于主题数据发生),我想将结果(主题)标记为用户交互的内容(写了一篇文章) .
所以,是的,还有另一种选择是加入 [Topic,Post] 以便结果是否标记为来自搜索,但这会破坏我缓存主题查询的能力(查询,即使没有连接,也比只为用户获取 id 更昂贵)
请注意上面概述的方法确实有效,他们只是觉得不够理想。
【问题讨论】:
-
也许你可以描述你为什么要做你正在做的事情。有时,提高抽象会揭示需求的简化(士力架 vs 比利时巧克力)。
标签: ruby-on-rails ruby-on-rails-3 activerecord associations has-many