基本上我有一个Collection模型和一个Post模型,其中Collection有很多帖子,一个Post属于很多集合。因此,我偶尔会使用@collection.posts
将帖子推送到<<
数组,以便将添加的帖子复制到集合中。现在有没有办法在推送到该阵列时在@collection.posts
中订购帖子?如果是,怎么样?
所有相关型号:
user.rb
class User < ActiveRecord::Base
has_many :posts, dependent: :destroy
has_many :collections, dependent: :destroy
end
post.rb
class Post < ActiveRecord::Base
belongs_to :user
has_many :collectables
has_many :collections, through: :collectables
end
collection.rb
class Collection < ActiveRecord::Base
belongs_to :user
has_many :collectables
has_many :posts, through: :collectables
end
collectable.rb
class Collectable < ActiveRecord::Base
belongs_to :post
belongs_to :collection
end
答案 0 :(得分:2)
我想将订单范围添加到关联的定义中会起作用:
# in collection.rb
has_many :posts,
-> { order('collectables.created_at DESC') },
through: :collectables