【问题标题】:How to get an ordered list of categories by names from IDs如何从 ID 中按名称获取类别的有序列表
【发布时间】:2015-05-09 16:16:00
【问题描述】:

我从数据库中加载数据,例如:

@cars = Car.where(...).order('created_at DESC').group_by { |r| r.voted.to_date }

然后,在一个视图中,我这样做:

- @cars.each do |key, arr|
  - categories = arr.uniq{|x| x.category_id} # so here I should get list of objects with uniuque category ID
  ...
  - arr.each do |car|
    ... print information about car ...

如何按姓名订购categories 列表?在car 模型中,有category_id 属性。

【问题讨论】:

  • Car和Category有关系吗?
  • 嗨@Masud,是的-汽车属于_to类别(但始终有一个)并且类别有很多汽车。

标签: ruby-on-rails ruby arrays activerecord model


【解决方案1】:

“如何按名称排序此类别列表?”这让人想起使用范围。

这是设置:在 category.rb 中

  scope :by_name, -> { order(name: :asc) }

现在您有一个参考句柄来抓取按升序排序的 category.name。

所以,在您看来,您可以为每辆 |car| 做类似的事情

<% if car.categories.by_name.any? %>
  <%= render category_name_partial", collection:...%>
     etc.

我用过'.any?'只是为了说明您有一个作为此操作的结果的排序集合,您列出的列表是根据“by_name”定义的范围按名称排序的。

【讨论】:

    【解决方案2】:

    为了使用category.name ASC。试试吧,

    @cars = Car.includes(:category).where(...).order('category.name ASC')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 2021-10-16
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      相关资源
      最近更新 更多