Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.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 根据ID数组对活动记录进行排序_Ruby On Rails_Arrays_Sorting_Activerecord - Fatal编程技术网

Ruby on rails 根据ID数组对活动记录进行排序

Ruby on rails 根据ID数组对活动记录进行排序,ruby-on-rails,arrays,sorting,activerecord,Ruby On Rails,Arrays,Sorting,Activerecord,我有一个ActiveRecord@grid 我有一个Hash@number rails控制台 1.9.3p385 :086 > Grids => Grids(unique_id: integer, price: float, availability: string, delivery: string, delivery_time: string, delivery_cost: float, special_offers: text, warr

我有一个ActiveRecord@grid

我有一个Hash@number

rails控制台

    1.9.3p385 :086 > Grids
     => Grids(unique_id: integer, price: float, availability: string,
     delivery: string, delivery_time: string, delivery_cost: float, 
     special_offers: text, warranty: text, created_at: datetime, updated_at: datetime) 


    => @numbers
    =>{7=>114, 9=>21, 12=>7, 13=>31, 14=>51, 16=>43, 18=>48, 21=>6, 22=>18, 
       24=>69, 27=>47, 30=>47, 32=>31, 33=>36} 
@数字散列只是唯一的\u id=>点击次数

1.9.3p385 :091 > @no =  @numbers.sort_by{|k,v| v}.reverse.map{|i| i[0]} 
              => [7, 24, 14, 18, 30, 27, 16, 33, 13, 32, 9, 22, 12, 21]
@否是唯一的\u id数组

@grid=grid.all

@grid is an activeRecord, I want to sort this active record based 
on the order of @no which is nothing but the unique_id in @grid.
我在试这个

@grid.sort_by{ |h| @no.index(h.unique_id) }
它不起作用,它说

ArgumentError:将NilClass与14进行比较失败


我知道有一些零比较正在进行。如何忽略这一点,或者有更好的方法吗?

之所以发生这种情况,是因为
@grid
包含一些
唯一的id
,而
@no
没有

替换

@grid = Grid.all

然后


首先从按id索引的网格关系创建哈希,然后从该索引的查找执行映射:

grid_index = @grid.index_by &:id
@no.map{|id| grid_index[id] } # possibly compact the resulting array after that
尝试:


没错,shweta!谢谢但是我在我的代码中创建了“禁止使用”网格。因此,严格来说,我想根据编号对网格进行排序。我还好吗?您可以在替换后执行
@grid.sort_by{h | h |@no.index(h.unique_id)}
。当我在创建网格期间没有编号时,我如何在这种情况下使用no…:conditions=>[“unique_id in(?),@no]…?感谢您的帮助,但看到了m_x的解决方案,它非常丰富。从活动记录中形成一个哈希,唯一的\u id作为密钥。现在,使用no值作为第一个形成的散列的键来构建activerecords数组。好东西!!你想在这方面帮我更多的忙,我必须在排序后对这个散列做很多工作。m_x,我正在研究你的解决方案,这有点像宾果游戏。让我试一下,然后走回去!老兄,我怎么能忽略结果数组中的零呢。忘记零吧,我会弄明白的。你的解决方案效果很好。谢谢。若要消除nils,请对生成的数组调用
compact
。不,您没有得到它。看看m_x的解决方案,品尝它的精华。
@grid.sort_by{ |h| @no.index(h.unique_id) }
grid_index = @grid.index_by &:id
@no.map{|id| grid_index[id] } # possibly compact the resulting array after that
@grid.where(:unique_id => @no).map(&:unique_id)