【发布时间】:2011-08-02 21:51:37
【问题描述】:
我有以下型号
class Post < ActiveRecord::Base
belongs_to :user, :counter_cache => true
belongs_to :subtopic
end
class Subtopic < ActiveRecord::Base
belongs_to :category
has_many :posts, :dependent => :destroy
end
class Category < ActiveRecord::Base
has_many :posts, :through => :subtopics
has_many :subtopics, :dependent => :destroy
end
在帖子/索引页面中,我想为列标题添加可点击排序。这很好,只是我显示了一些两层深的信息:
- 帖子属性
- 子主题名称
- 类别名称
- 子主题名称
我希望表格的“类别”列是可点击的,这样我就可以显示所有按类别排序的帖子。不幸的是,当我构造查询的“order by”部分时,我似乎无法为类别名称找到任何东西。我可以深入一层
@posts = Post.includes(:user, :subtopic => :category).paginate(:page =>1, :order => 'subtopics.name ASC')
这会返回我想要的结果。当我尝试更深一层时
@posts = Post.includes(:user, :subtopic => :category).paginate(:page =>1, :order => 'subtopic.categories.name ASC')
我收到PGError: ERROR: schema "subtopic" does not exist。复数子主题给出了同样的错误。我觉得我错过了一些明显的东西。谁能指出来?
旁注:异味警报。我知道。如果您也有关于如何使此代码更清洁的建议,那将非常受欢迎。我知道得墨忒耳法则,但我不知道如何在不破坏它的情况下获得我想要的最终结果。
更新 8/3:ActiveRecord 或 PostgreSQL 在控制器操作中导致另一个错误。以下语句在数据库控制台中有效:
SELECT * from "posts" LEFT OUTER JOIN "users" ON "users"."id" = "posts"."user_id" LEFT OUTER JOIN "subtopics" ON "subtopics"."id" = "posts"."subtopic_id" LEFT OUTER JOIN "categories" ON "categories"."id" = "subtopics"."category_id" ORDER BY categories.name ASC LIMIT 30;
上面的 SQL 语句大约是由下面的语句生成的。下面的 rails 代码在 rails console 中有效,但在我的 Post#index 控制器操作中不是
@posts = Post.includes(:user, :subtopic => :category).paginate(:page =>1, :order => 'categories.category_name ASC', :conditions => ["posts.flags_count < ?", Flag.flag_threshold] )
错误:https://gist.github.com/1124135
:order => 'categories. ...' 和 :order => 'subtopics. ...' 会出现此错误,但:order => (column in posts) 会出现不会。 ActiveRecord 生成的 JOIN 语句看起来有问题,但实际的 SQL 语句看起来应该对我有用。
更新 8/4:当我在我的环境中启用 SQL 日志记录时(使用 a shell script),我可以看到 ActiveRecord 在 rails console 和(一个控制器)中生成的 SQL 查询rails server 不同。
具体来说,在服务器上,AR 会在某些列前添加“post.”,例如 posts.users.display_name 而不是 users.display_name。这只发生在服务器上,并且只有当我在查询中包含:order => (non-posts column) ASC/DESC
【问题讨论】:
-
对于那些有类似问题的人,我决定将第二个问题拆分为一个单独的问题,在这里:stackoverflow.com/questions/6948966/…
标签: ruby-on-rails activerecord associations