Created
December 24, 2013 08:10
-
-
Save tbaba/8110223 to your computer and use it in GitHub Desktop.
Railsのas_jsonをもうちょっと便利に使うオプション ref: http://qiita.com/tbaba/items/ea44025b056f708ab0b4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
user.as_json.merge(full_name: user.full_name) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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”} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
user.as_json.delete_if{|k, v| k == 'email' } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
user.as_json(except: 'email') | |
=> {"first_name"=>"User1", "id"=>1, "last_name"=>"USER1”} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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