【发布时间】:2016-04-14 23:12:04
【问题描述】:
category 和 post 之间存在多对多关系。
连接表是category_post_relationships。
class Post < ActiveRecord::Base
has_many :categories, through: :category_link_relationships
has_many :category_post_relationships , :dependent => :destroy
end
class Category < ActiveRecord::Base
has_many :posts, through: :category_link_relationships
has_many :category_post_relationships , :dependent => :destroy
end
class CategoryPostRelationship < ActiveRecord::Base
belongs_to :post
belongs_to :category
end
如果我有一个分类,该分类可以查询category.posts的所有帖子。我想通过连接表category_link_relationships 的created_at 对这些帖子进行排序。每个类别和帖子只能有一个记录。我想按关联关系记录的created_at列对链接进行排序。
例如,帖子 1 已创建并与类别 A 相关联。
然后,帖子 1 与类别 B 相关联。
然后创建帖子 2 并将其关联到类别 B。
B 类现在有帖子 1 和帖子 2。我想按关系的 created_at 而非帖子的 created_at 对帖子 1 和帖子 2 进行排序。
谢谢。
【问题讨论】:
-
首先你应该使用
has_and_belongs_to_many,其次:所以你需要为一个类别按特殊顺序获取所有帖子?@category.posts之类的东西? -
是的。我需要为一个类别按特殊顺序获取所有帖子。特殊顺序取决于该类别与其每个帖子之间关系的
created_at。 -
现在您不能将关联更改为 HABTM?
-
没有。我需要这个连接表。
-
添加了答案,看看吧
标签: sql ruby-on-rails sorting