ruby-on-rails - 关系 belongs_to 上的 activerecord where 子句

标签 ruby-on-rails ruby activerecord

我不太擅长 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/

相关文章:

ruby-on-rails - 适用于 Ruby on Rails 的 Facebook 营销 API(广告)

ruby-on-rails - `require' : no such file to load -- mkmf (LoadError)

ruby - cascade_callbacks 不适用于 mongoid 中的嵌入式文档

ruby-on-rails - Rails Active Record 项目分区

mysql - ActiveRecord 的分布式事务边界

php - 如何在 GridView 上显示过滤模型关系

ruby-on-rails - 选择从最后一次插入数据库的日期开始的过去 12 个月的行

ruby-on-rails - 如何获取特定用户的所有帖子

ruby-on-rails - Rails - Action Cable 是否需要 Rails 5?

ruby - 在数组中查找最常见的字符串