【问题标题】:Ruby: group an array of ActiveRecord objects in a hashRuby:将一组 ActiveRecord 对象分组到哈希中
【发布时间】:2011-03-30 18:33:14
【问题描述】:

我想将一个 ActiveRecord 对象数组分组到一个散列中,该散列具有一个易于在 SQL 语句之后查询的接口,如下所示:

SELECT name,value from foo where name IN ('bar', 'other_bar') LIMIT 2;

查询之后,我想要一个可以去的哈希:

foo[:bar] # output: value1
foo[:other_bar] # output: value2

用 ActiveRecord 收集对象并将它们分组以便我可以使用上面的界面的最佳方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    在 Rails 2 中

    foos = Foo.all :select => "name, value",
                   :conditions => ["name in (?)", %w(bar other_bar)],
                   :limit => 2
    

    在 Rails 3 中

    foos = Foo.where("name in (?)", %w(bar other_bar)).select("name, value").limit(2)
    

    然后

    foo = Hash[foos.map { |f| [f.name.to_sym, f.value] }]
    

    foo = foos.inject({}) { |h, f| h[f.name.to_sym] = f.value; h }
    

    或在 Ruby 1.9 中

    foo = foos.each_with_object({}) { |f, hash| hash[f.name.to_sym] = f.value }
    

    【讨论】:

      【解决方案2】:

      如果我理解正确的话:

      foo = Hash[Foo.find(:all, :limit => 2, :select => "name, value", :conditions => ["name in ('bar', 'other_bar')"]).map { |s| [s.name.intern, s.value] }]
      

      【讨论】:

      • 请注意,这只适用于 Ruby 1.9;对于 Ruby 1.8,您必须使用 Hash[ *foo.flatten ]
      • @rubyprince 是对的,我在运行 1.8.7 的脚本/控制台中对此进行了测试。
      • 我的错,我应该说1.8.6; Ruby 1.8.7 真是一头奇异的野兽。
      【解决方案3】:
      Hash[result.map { |r| [r[:name].to_sym, r[:value]] } ]
      

      【讨论】:

        【解决方案4】:
        models.inject({}) {|h,m| h[ m.name.to_sym ] = m.value; h }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-26
          • 1970-01-01
          • 1970-01-01
          • 2015-11-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-11
          相关资源
          最近更新 更多