Skip to content

Instantly share code, notes, and snippets.

@tbaba
Created December 24, 2013 08:10
Show Gist options
  • Save tbaba/8110223 to your computer and use it in GitHub Desktop.
Save tbaba/8110223 to your computer and use it in GitHub Desktop.
Railsのas_jsonをもうちょっと便利に使うオプション ref: http://qiita.com/tbaba/items/ea44025b056f708ab0b4
irb(main):033:0> user = User.first
=> #<User id: 1, first_name: ‘Tatsuro’, last_name: ‘Baba’, email: ‘harakirisoul@gmail.com’>
irb(main):034:0> user.as_json
=> {"email"=>"user_1@example.com", "first_name"=>"User1", "id"=>1, "last_name"=>"USER1"}
user.as_json.merge(full_name: user.full_name)
irb(main):035:0> user.as_json(methods: 'full_name')
=> {"email"=>"user_1@example.com", "first_name"=>"User1", "id"=>1, "last_name"=>"USER1”, “full_name”=>”User1 USER1”}
user.as_json.delete_if{|k, v| k == 'email' }
user.as_json(except: 'email')
=> {"first_name"=>"User1", "id"=>1, "last_name"=>"USER1”}
user.as_json(only: ['id', 'first_name', 'last_name'])
=> {"first_name"=>"User1", "id"=>1, "last_name"=>"USER1”}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment