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