Ruby on rails 是否在将项目添加到数组时将其排列在该数组中?
基本上我有一个集合模型和一个帖子模型,其中一个集合有许多帖子,而一个帖子属于许多集合。因此,我偶尔会使用Ruby on rails 是否在将项目添加到数组时将其排列在该数组中?,ruby-on-rails,arrays,ruby,Ruby On Rails,Arrays,Ruby,基本上我有一个集合模型和一个帖子模型,其中一个集合有许多帖子,而一个帖子属于许多集合。因此,我偶尔会使用将posts推送到@collection.posts数组中,我想在关联的定义中添加一个order作用域是可行的: # in collection.rb has_many :posts, -> { order('collectables.created_at DESC') }, through: :collectables 您的联接表是什么样子的?它只
将posts推送到@collection.posts
数组中,我想在关联的定义中添加一个order作用域是可行的:
# in collection.rb
has_many :posts,
-> { order('collectables.created_at DESC') },
through: :collectables
您的联接表是什么样子的?它只有两列collection\u id
和post\u id
?或者它是否有其他专栏,比如在
上创建的?@spickermann实际上我在这里问了一个更详细的问题——但我想没有人回答,因为它太长了。所以我决定问一个更切题的问题。尽管如此,我还是用所有相关的模型代码更新了这个问题您的收藏品数据库表有哪些列?@spickermann这些列是post\u id
,collection\u id
,created\u at
和updated\u at
这听起来像是rails的概念问题。你需要使用内存存储。是否使用会话或数据库来执行此操作取决于此数据是否需要跨多个请求持久化。Doh!这很简单。我甚至不知道关联定义接受的范围。非常感谢!为什么不简单地按ID订购呢?@Ven:因为收藏品
表没有ID
(根据OP上面的评论)。并且post\u id
或collection\u id
的顺序不一定与向收藏添加帖子的日期相同。
class Post < ActiveRecord::Base
belongs_to :user
has_many :collectables
has_many :collections, through: :collectables
end
class Collection < ActiveRecord::Base
belongs_to :user
has_many :collectables
has_many :posts, through: :collectables
end
class Collectable < ActiveRecord::Base
belongs_to :post
belongs_to :collection
end
# in collection.rb
has_many :posts,
-> { order('collectables.created_at DESC') },
through: :collectables