Rails:如何对多对多关系进行排序 [英] Rails: How to sort many-to-many relation
问题描述
我在模型用户和图片之间存在多对多关系.这些通过称为Picturization的联接表链接.
I have a many-to-many relationship between a model User and Picture. These are linked by a join table called Picturization.
如果我获得单个图片的用户列表,即picture.users->如何确保通过创建Picturization行(即,图片与图片关联的顺序)对获得的结果进行排序用户).如果我想按修改顺序获得此更改,该如何更改?
If I obtain a list of users of a single picture, i.e. picture.users -> how can I ensure that the result obtained is sorted by either creation of the Picturization row (i.e. the order at which a picture was associated to a user). How would this change if I wanted to obtain this in order of modification?
谢谢!
修改 也许像
picture.users.where(:order => "created_at")
- 但是这个created_at指的是图片中的created_at
推荐答案
在图形化表中还增加了一个列,例如 sequence ,并将排序顺序定义为Picturization中的默认范围
Have an additional column something like sequence in picturization table and define sort order as default scope in your Picturization
default_scope :order => 'sequence ASC'
如果您要基于Modify_at的默认排序顺序,请使用以下默认范围
If you want default sort order based on modified_at then use following default scope
default_scope :order => 'modified_at DESC'
这篇关于Rails:如何对多对多关系进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!