我不擅长sql,对rails还比较陌生。这个

Case
  attr_accessible client_id
  belongs_to Client

Client
  attr_accessibe name
  has_many Cases

我可以直接按客户ID查询并按预期取回记录
Case.where(client_id: 1)

但我想按client.name查询
Case.where(client.name => "Foo")

这给了我一个错误,告诉我客户不是一个案例的方法。
Undefined method or local variable

最终,我要做的是非常简单的:得到属于客户机“foo”的第一个案例。我希望使用的查询是这样的。
Case.where(client.name => "Foo").first

应该是什么?

最佳答案

Case.joins(:client).where(clients: { name: 'foo' })

此查询将连接case表上的客户机(消除没有任何客户机关联的案例),并添加where子句"where clients.name = 'foo'"
在人类语言中,此查询执行以下操作:
获取至少有一个客户机的名称与“foo”严格相等(区分大小写)的案例
注意复数/单数:
在联接/包含中,使用与模型中声明的关系相同的名称
在where子句中,始终使用关系的复数形式(实际上是表名)
附加信息:
可以在where子句中使用值数组:
Case.joins(:client).where(clients: { id: [1,2,5] })

.joins.includes之间的差异:Rails :include vs. :joins

10-07 19:33
查看更多