【发布时间】:2012-09-21 17:55:50
【问题描述】:
我正在使用 Ruby on Rails 3.2.2 并且我有以下 has_many :through 关联以便“按类别排序文章”:
class Article < ActiveRecord::Base
has_many :category_associations # Association objects
has_many :associated_categories, :through => :category_associations # Associated objects
end
class CategoryAssociation < ActiveRecord::Base
acts_as_list :scope => 'category_id = #{category_id} AND creator_user_id = #{creator_user_id}'
belongs_to :associated_article
belongs_to :creator_user, :foreign_key => 'creator_user_id'
end
在检索 associated_categories 时,我想加载用户创建的 category_associations 对象(注意:创建者用户由 creator_user_id 数据库表中的 creator_user_id 列标识) 因为我需要显示 position 值(注意:position 属性,Integer,是 act_as_list gem 所必需的,它是category_associations 数据库表中的列)“靠近”每篇文章的标题。
实际上,在我看来,我想以适当和性能的方式制作类似以下的东西(注意:它是假设@articles 中的每篇文章都被用户“分类”——用户指的是category_associations 的创建者用户):
<% @articles.each do |article| %>
<%= link_to(article.title, article_path(article)) %> (<%= # Display the article position in the given category %>)
<% end %>
也许,我应该“创建”和“处理”一个 自定义数据结构(或者,也许,我应该做一些其他的......),但我不知道如何继续完成什么我正在寻找。
此时我认为急切加载对我的情况来说是一个好方法,因为我可以避免N + 1 queries problem,因为我必须在关联对象上声明更多条件以便:
- 检索由给定用户创建的关联对象的特定属性值(在我的例子中是指
position值); - “关联”(以某种方式,使
position值适合显示)每个特定属性值到对应的关联对象。
【问题讨论】:
-
带有包含的默认范围?
-
@apneadiving - 你如何用
scope方法做到这一点?你能发布一个例子,因为我的案例(我认为)是一个人为的案例吗?
标签: ruby-on-rails ruby ruby-on-rails-3 associations eager-loading