ran*_*its 3 ruby ruby-on-rails
我想将一个ActiveRecord对象数组分组到一个哈希中,该哈希的接口在查看如下所示的SQL语句之后很容易查询:
SELECT name,value from foo where name IN ('bar', 'other_bar') LIMIT 2;
Run Code Online (Sandbox Code Playgroud)
在那个查询之后,我想要一个哈希,我可以去:
foo[:bar] # output: value1
foo[:other_bar] # output: value2
Run Code Online (Sandbox Code Playgroud)
使用ActiveRecord收集对象的最佳方法是什么,并将它们分组,以便我可以使用上面的界面?
rub*_*nce 15
在Rails 2中
foos = Foo.all :select => "name, value",
:conditions => ["name in (?)", %w(bar other_bar)],
:limit => 2
Run Code Online (Sandbox Code Playgroud)
在Rails 3中
foos = Foo.where("name in (?)", %w(bar other_bar)).select("name, value").limit(2)
Run Code Online (Sandbox Code Playgroud)
然后
foo = Hash[foos.map { |f| [f.name.to_sym, f.value] }]
Run Code Online (Sandbox Code Playgroud)
要么
foo = foos.inject({}) { |h, f| h[f.name.to_sym] = f.value; h }
Run Code Online (Sandbox Code Playgroud)
或者在Ruby 1.9中
foo = foos.each_with_object({}) { |f, hash| hash[f.name.to_sym] = f.value }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6646 次 |
| 最近记录: |