ActiveRecord :: Relation不能在join的where子句中使用命名关联 [英] ActiveRecord::Relation cannot use named association in where clause of join

查看:146
本文介绍了ActiveRecord :: Relation不能在join的where子句中使用命名关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在与联接关联的where子句中使用命名关联?

How do I use a named association in the where clause associated with a join?

class Pet < ActiveRecord::Base
    belongs_to :owner
end

class Owner < ActiveRecord::Base
    has_many :dogs, :class_name => 'Pet', :foreign_key =>  :owner_id
end


Owner.joins(:dogs).where(:dogs => {:name => 'fido'}).to_sql

生成:

"SELECT `owners`.* FROM  `owners`  INNER JOIN `pets` ON `pets`.`owner_id` = `owners`.`id` WHERE  (`dogs`.`name` = 'fido')"

请注意,WHERE子句在dogs表而不是pets表中查找

Note that the WHERE clause is looking in the dogs table instead of the pets table

供参考:

http://guides.rubyonrails.org/active_record_querying.html#specification-conditions-joined-tables

推荐答案

这似乎是预期的行为-您需要在哈希中指定表名,而不是关联名.这有点不幸,因为我认为,构造查询将更多地基于其模型定义,而不是基于其前面的架构,这将是有用的.

It appears this is the expected behavior - you need to specify the table name in the hash, not the association name. This is a little unfortunate because I think it'd be useful construct queries based more on their model definition and less on schema they sit in front of.

这篇关于ActiveRecord :: Relation不能在join的where子句中使用命名关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆