Skip to content

Instantly share code, notes, and snippets.

@lanrion
Created June 10, 2014 06:08
Show Gist options
  • Save lanrion/a525373b5e040c9a3f86 to your computer and use it in GitHub Desktop.
Save lanrion/a525373b5e040c9a3f86 to your computer and use it in GitHub Desktop.
导出id,name json格式

有一个简单的需求:

数据库有一个表User(id, name),需要导出:

 {
   id1 => name1,
   id2 => name2
 }

第一种写法:

User.pluck("id,name").flatten.each_slice(2).inject({}) do |hash, users|
  id, name = users
  hash[id]=name
  hash
end

第二种写法:

 Hash[*User.all.map{|_|[_.id, _.name]}.flatten]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment