Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.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 在ActiveRecord中排序一对多关系_Ruby On Rails_Rest_Activerecord - Fatal编程技术网

Ruby on rails 在ActiveRecord中排序一对多关系

Ruby on rails 在ActiveRecord中排序一对多关系,ruby-on-rails,rest,activerecord,Ruby On Rails,Rest,Activerecord,我第一次用ActiveRecord设计API。我有一个父对象,它有许多子对象。子对象属于父对象:counter\u cache=>true 当前,API返回一个JSON结构,其中包含父级及其所有子级的数组,按时间排序。我想将API更改为默认情况下不返回所有子对象。理想情况下,API应该足够灵活,能够返回,例如,child#1、#4和#6-22,JSON响应将指示这些位置 我的第一反应是向数据库中包含整数索引的每个子对象添加一列。我可以在创建时使用父级的计数器\u缓存值分配这个整数。这样一来,第一

我第一次用ActiveRecord设计API。我有一个父对象,它有许多子对象。子对象
属于父对象
:counter\u cache=>true

当前,API返回一个JSON结构,其中包含父级及其所有子级的数组,按时间排序。我想将API更改为默认情况下不返回所有子对象。理想情况下,API应该足够灵活,能够返回,例如,child#1、#4和#6-22,JSON响应将指示这些位置

我的第一反应是向数据库中包含整数索引的每个子对象添加一列。我可以在创建时使用父级的
计数器\u缓存
值分配这个整数。这样一来,第一个孩子将是0,下一个是1,依此类推

这是最好的方法吗

以下是我的型号(型号名称已更改):

类父级:销毁
结束
类Childtrue
结束
假设我想通过如下迁移向名为“ordinal”的子级添加一个整数列:

class AddOrdinalToChild < ActiveRecord::Migration
  def self.up
    add_column :children, :ordinal, :integer, :default => 0
  end

  def self.down
    remove_column :children, :ordinal
  end
end
class AddOrdinalToChild0
结束
def自动关闭
删除_列:子项,:序数
结束
结束

我该如何填充
ordinal
,以便对于属于某个父项的每个子项,ordinal记录该子项创建/分配给该父项的顺序?

到目前为止,您拥有的代码将非常有用。我添加了一些模型代码,但目前我没有任何代码尝试解决此问题,我当前的代码是对
作为\u json
的一系列简单调用。任何解决方案或多或少都不会涉及旧代码。
class AddOrdinalToChild < ActiveRecord::Migration
  def self.up
    add_column :children, :ordinal, :integer, :default => 0
  end

  def self.down
    remove_column :children, :ordinal
  end
end