我不太擅长 sql,对 Rails 也比较陌生。
Case
attr_accessible client_id
belongs_to Client
Client
attr_accessibe name
has_many Cases
我可以直接通过client_id查询,并按预期取回一条记录
Case.where(client_id: 1)
但是我想通过client.name查询
Case.where(client.name => "Foo")
这给我一个错误,告诉我 client 不是 case 的方法。
Undefined method or local variable
最终,我要做的非常简单:获取属于客户“Foo”的第一个案例。我希望使用的查询是这样的。
Case.where(client.name => "Foo").first
应该是什么?
最佳答案
Case.joins(:client).where(clients: { name: 'foo' })
此查询将在案例表中加入客户(消除没有任何客户关联的案例)并添加 where 子句 "where clients.name = 'foo'"
在人类语言中,这个查询会:
Get the Cases having at least one Client having the name strictly equal (case-sensitive) to 'foo'
注意复数/单数:
在连接/包含中,使用与模型中声明的关系相同的名称
在 where 子句中,始终使用关系的复数形式(实际上是表名)
附加信息:
您可以在 where 子句中使用值数组:
Case.joins(:client).where(clients: { id: [1,2,5] })
.joins
和.includes
的区别:Rails :include vs. :joins
关于ruby-on-rails - 关系 belongs_to 上的 activerecord where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18900935/