Ruby:将数组或散列转换为activerecord关系

时间:2017-11-15 14:34:14

标签: ruby-on-rails ruby activerecord

我正在尝试将哈希转换为activerecord关系,但我无法这样做。我打算使用activerecord关系进行排序,然后过滤Category表。最终目标是创建一个实例方法来过滤前5个访问类别,然后我可以在控制器中使用/调用。这就是我的想法:

类别模型:

def top_5_visited
        Article.joins(:categories).group('categories.name').sum(:impressions_count)
// Add sort
// Limit to top 5 
end

类别控制器:

@categories = Category.top_5 visited

将通过以下查询创建哈希 {"Simula"=>7, "Haskell"=>5, "JavaScript"=>10, "C#"=>112}

total_count = Article.joins(:categories).group('categories.name').sum(:impressions_count)

我还尝试使用sort_by方法将其转换为数组:

total_count_sorted = total_count.sort_by {|_key, value| value}

我用google搜索"将数组转换为activerecord关系"并引用了this帖子,但测试了这个:

Category.where(id: total_count_sort.map(&:id))
在rails控制台中,

会出现此错误:

  

NoMethodError:[" Simula",7]的未定义方法ID:数组

2 个答案:

答案 0 :(得分:3)

你想做什么从反面(类别)开始,并在ORDER子句中使用聚合。

Category.joins(:articles)
        .order('SUM(articles.impressions_count) DESC')
        .group(:id)
        .limit(5)
irb(main):005:0> Category.joins(:articles).order("SUM(articles.impressions_count) DESC").group('categories.id').limit(5)
  Category Load (1.5ms)  SELECT  "categories".* FROM "categories" INNER JOIN "articles" ON "articles"."category_id" = "categories"."id" GROUP BY categories.id ORDER BY SUM(articles.impressions_count) DESC LIMIT $1  [["LIMIT", 5]]
=> #<ActiveRecord::Relation [#<Category id: 4, name: "C#", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">, #<Category id: 3, name: "JavaScript", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">, #<Category id: 1, name: "Simula", created_at: "2017-11-15 15:03:37", updated_at: "2017-11-15 15:03:37">, #<Category id: 2, name: "Haskell", created_at: "2017-11-15 15:06:32", updated_at: "2017-11-15 15:06:32">]>

你应该创建一个类方法 - 而不是实例方法,因为这基本上只是一个范围,并且调用实例没有意义。

class Category < ApplicationRecord
  has_many :articles

  def self.order_by_article_impressions
    self.joins(:articles)
        .order('SUM(articles.impressions_count)')
        .group(:id)
  end

  def self.top_5_visited
    order_by_article_impressions.limit(5)
  end

  # Or use `scope` which is just syntactic sugar
  scope(:top_5_visited) -> { order_by_article_impressions.limit(5) }
end

答案 1 :(得分:0)

将代码更改为:

public void Fill()
    {
        List<testowa1> lista = new List<testowa1>();
        var item = new testowa1()
        {
            ID = 1,
            Nazwa = "Pierwszy",
            Cena = new testowa2()
            {
                Cena = 32.22M
            }
        };
        lista.Add(item);
        lista.Add(item);
        lista.Add(item);
        lista.Add(item);

        dataGridView1.DataSource = lista;
    }

    public class testowa1
    {
        public int ID { get; set; }
        public string Nazwa { get; set; }
        public testowa2 Cena { get; set; }
    }
    public class testowa2
    {
        public decimal Cena { get; set; }
    }