使用acts_as_taggable_on自定义JSON响应

时间:2016-02-05 03:16:25

标签: ruby-on-rails json

我刚刚在我的应用中实施了acts_as_taggable_on,现在我正在尝试修剪我的JSON响应,因此它不会返回所讨论模型的所有内容。这是我的as_json方法的样子:



def as_json(options={})
  super(:only => [:serial_number],
    :include => {
      :device_functions => { :only => [:can_scan, :can_brute] },
	  :scan_options => { :methods => :scan_ip_list}
	}
  )
end




目前返回:



{
  "serial_number": "abcdefg12345",
  "device_functions": [
    {
      "can_scan": true
    }
  ],
  "scan_options": [
    {
      "id": 1,
      "device_id": 11,
      "created_at": "2016-02-05T02:26:26.090Z",
      "updated_at": "2016-02-05T02:26:26.090Z",
      "scan_ip_list": [
        "10.10.10.100-110",
        "10.10.10.1"
      ]
    }
  ]
}




我想摆脱我不需要的额外数据,例如iddevice_idcreated_atupdated_at

此外,使用:only =>查找:device_functions响应,但我必须使用:methods => :scan_options,因为我使用acts_as_taggable_on ...至少那些我读过的内容是唯一一个返回内容的选项(我也试过了:only =>:include =>但是他们返回了一个空哈希:



{
  "serial_number": "abcdefg12345",
  "device_functions": [
    {
      "can_scan": true
    }
  ],
  "scan_options": [
    {}
  ]
}




1 个答案:

答案 0 :(得分:1)

您只需要在:only哈希中添加:scan_options选项:

# ...
      :scan_options => { :methods => :scan_ip_list, :only => :scan_ip_list }

另外,FWIW,您可能应该合并到option,以防您想要提供一些自己的选项,所以:

# ...
  super options.merge( :only => ...etc.