Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.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 rails如何生成数组以显示类别_Ruby On Rails_Arrays_Categories - Fatal编程技术网

Ruby on rails rails如何生成数组以显示类别

Ruby on rails rails如何生成数组以显示类别,ruby-on-rails,arrays,categories,Ruby On Rails,Arrays,Categories,我从我的半链接模型中得到了以下对象列表,如: @itemhl = HalfLink.find_all_by_item_id(@item, :include => :other_item) id | item_id | other_item_id | other_item_category_id 1 | 1 | 2 | 1 2 | 1 | 3 | 4 3 | 1 | 4

我从我的半链接模型中得到了以下对象列表,如:

        @itemhl = HalfLink.find_all_by_item_id(@item, :include => :other_item)

id | item_id | other_item_id | other_item_category_id
1  | 1       | 2             | 1
2  | 1       | 3             | 4
3  | 1       | 4             | 3
4  | 1       | 6             | 1
5  | 1       | 8             | 3
6  | 1       | 7             | 4
我想将其转换为在我的视图中显示为:

类别1的名称

其他_项目1的名称

其他_项目6的名称

类别3的名称

其他_项目4的名称

其他_项目8的名称

类别4的名称

其他_项目3的名称

其他项目7的名称

它仅显示存在的类别,以及按唯一类别分组

我知道通常的方法是链接ActiveRecord,这样我就可以做Category.other_项目,但由于其他问题,目前这并不实用

有没有其他方法来设置这个?我应该构建一个数组吗

我还有以下几行:

    @item_categories = @itemhl.map{|c| c.other_item.category.name }.uniq

实际上,您不必在模型或控制器代码中进行太多修改,您需要在视图中添加一些代码:

@itemhl = HalfLink.find_all_by_item_id(@item, :include => :other_item, :order => 'other_item_category_id asc')
按类别id获取项目顺序。然后在视图中,根据一些简单算法显示类别名称

previous_category = nil
@itemh1.each do |item|
  if previous_category == nil || previous_category != item.category
    ouput the category_name
    previous_category = item.category
  end

  display  item name

end

您已经具有检索所需项目的代码:

@itemhl = HalfLink.find_all_by_item_id(@item, :include => :other_item)
现在,要将其转换为更具表现力的形式,您可以执行以下操作:

@items_grouped_by_categories = @itemhl.group_by {|itemhl| itemhl.other_item.category.name}
# now you have a @items_grouped_by_categories, which resembeles this
# {
#    category1_name => [itemhl1, itemhl4],
#    category3_name => [itemhl3, itemhl5],
#    .....
# }

@items_grouped_by_categories.each do |category_name, itemhls|
   # output the category_name

   itemhls.each do |itemhl|
     other_time = itemhl.other_item
     # output the other item
   end
end

您也可以在此处使用group_。参考文献:,嗨@rubishgupta,我看了一下组员,但不知道如何合并。如果你能在下面补充一个答案,我将不胜感激