Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 是否在将项目添加到数组时将其排列在该数组中?_Ruby On Rails_Arrays_Ruby - Fatal编程技术网

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