简体   繁体   中英

Ruby on Rails - as_json remove some attributes

I have a response ready with some attributes. However, I dont want some of them to get passed on to the response. How do I do that? I think I need to use except somehow.

The :only and :except options can be used to limit the attributes included, and work similar to the attributes method.

 user.as_json(only: [:id, :name]) # => { "id" => 1, "name" => "Konata Izumi" } user.as_json(except: [:id, :created_at, :age]) # => { "name" => "Konata Izumi", "awesome" => true }

You can use except parameter of as_json like so:

2.5.0 :001 > {foo: 1, bar: 2, baz: 3}.as_json(except: [:baz])
 => {"foo"=>1, "bar"=>2} 

You can use only or except for your use case.

Something like below should work:

#<Address id: nil, 
          address1: nil, 
          address2: nil,
          city_name: nil, 
          zipcode: nil, 
          phone: nil, 
          state_id: nil, 
          country_id: nil, 
          created_at: nil, 
          updated_at: nil, 
          address_type: nil, 
          latitude: nil, 
          longitude: nil,
          city_id: nil, 
          locality: nil>
json = address.as_json(only: %i[id 
                                address1 
                                address2
                                locality 
                                city_id 
                                zipcode
                                address_type
                                latitude 
                                longitude],
                           methods: [:city_slug])  # yes, you can use methods as attributes also

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM