返回关联计数,而不是所有关联本身

时间:2018-07-15 00:39:25

标签: ruby-on-rails json api

因此,Object有许多properties,而property属于Object。目前是协会。现在,当我使用Object.all渲染所有对象并包括:properties关联时,我将在渲染的JSON中获得property模型的所有属性。但是我真的不需要。我需要的是关联的数量。即,仅存在与任何一个对象相关联的属性数量。这是我的代码:

@objects = Object.all
respond_to do |format|
  format.json { 
    render json: @objects.to_json(:include => [:properties]) 
  }
end

这会产生类似的结果。当前只有1个property与1个现有的object相关联,正如您在JSON中看到的那样,我得到了许多与相关的properties相关的信息,(或更确切地说, ,财产),我不需要也不想要。

"id": 2,
"attrs_go_here": "asdfsdaf"
"created_at": "2018-07-14T23:51:55.161Z",
"updated_at": "2018-07-14T23:51:55.161Z",
"properties": [
    {
        "id": 5,
        "more_attributes": "asdfasdfasdf"
        "created_at": "2018-07-14T23:53:14.917Z",
        "updated_at": "2018-07-14T23:53:14.917Z"
     }
]

但是,相反,我想要这样的东西,我可以得到关联的数量:

"id": 2,
"attrs_go_here": "asdfsdaf"
"created_at": "2018-07-14T23:51:55.161Z",
"updated_at": "2018-07-14T23:51:55.161Z",
"properties": 1

我之所以只想要这个数字,是因为可能与任何一个对象关联数十万个属性。而且我觉得,当我只需要一个对象及其属性之间存在的关联数时,呈现与该对象相关的所有属性的所有属性就会非常慢。

2 个答案:

答案 0 :(得分:0)

为简单起见,此答案将“ properties”替换为“ properties_count”

Object.select('objects.*', 'COUNT(properties.id) as properties_count')
      .joins(:properties)
      .group('objects.id')

答案 1 :(得分:0)

为模型Object

添加方法
def properties_count
  self.properties.count
end

然后由您的控制器执行

render json: @objects.to_json(methods: [:properties_count]) 

尽管我不确定可能的n + 1。在这种情况下,您应该使用

@objects = Object.includes(:properties).all

编辑 从技术上讲,它不打算提供参数to_json只是为了获取。但是您可以按照以下方式做一些事情:

class Object
  attr_accessor :attribute

  def method_with_params(attribute = nil)
    attribute ||= attribute
    # rest of your code
  end
end


@object.attribute = 'foodbar'
render json: @object.to_json(methods: [:method_with_params]