【问题标题】:Returning count of associations instead of all associations themselves返回关联的计数而不是所有关联本身
【发布时间】:2018-07-15 00:39:25
【问题描述】:

所以,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

我只想要这个数字的原因是因为可能有数十万个属性与任何一个对象相关联。当我首先需要的是对象与其属性之间的关联数量时,我觉得渲染与对象关联的所有属性的所有属性真的很慢。

【问题讨论】:

  • 可以添加属性表的架构吗?

标签: ruby-on-rails json api


【解决方案1】:

为你的模型添加一个方法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]

)

【讨论】:

  • 嘿,非常感谢你的工作!另一个问题:如果其中一个方法接受参数,你怎么能做同样的事情(在to_json 方法中输入方法)?例如:@objects.to_json(methods: [:properties_count, :method_with_params(args)]) 这当然是不正确的。它会引发语法错误。我只是想知道这是否可能。即使没有,你也解决了我的问题,非常感谢
【解决方案2】:

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

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

【讨论】:

  • 我收到一条错误消息:PG::UndefinedTable: ERROR: missing FROM-clause entry for table "properties 我应该运行迁移以将properties 添加到object 模型吗?这是我唯一能想到的解决此错误的方法,但这样做会破坏关联的全部意义。另外,您会使用数据类型来添加包含集合的列吗?我有点困惑。
猜你喜欢
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多