Rails as_json with conditions

前端 未结 2 890
说谎
说谎 2020-12-12 00:07

In my application, :foos have many :bars, and I\'m serializing each foo as JSON like so:

@foo.as_json(
  except: [:created_at, :upd         


        
相关标签:
2条回答
  • 2020-12-12 00:24

    you use as_json with conditions for customize json response for some actions, but model serializers for default json response that you needed for the most responses.

    Read these Model_Serializer VS. as_json, record-serializers-from-scratch.

    0 讨论(0)
  • 2020-12-12 00:45

    I think you could try add some method like active_bars which will return exactly what you need like:

    def active_bars
      bars.where active: true
    end
    

    or you could even add new relation:

    has_many :active_bars, -> { where active: true }, class_name: '..', foreign_id: '..'
    

    and then you will be able write:

    @foo.as_json(
      except: [:created_at, :updated_at], 
      include: { 
        active_bars: { only: [:ip_addr, :active] }
      }
    )
    
    0 讨论(0)
提交回复
热议问题