Rails 4.2查询3个模型,belongs_to和has_one无法根据子属性获取父项

时间:2015-04-16 20:28:12

标签: mysql ruby-on-rails ruby

我有3个具有以下关系的模型:

终端用户

class EndUser < ActiveRecord::Base
   belongs_to :account, :dependent=>:destroy

帐户

class Account < ActiveRecord::Base
   has_one :api_key

ApiKey

class ApiKey < ActiveRecord::Base
   belongs_to :account

在控制台中,我一直尝试使用此ORM查询基于EndUser的属性ApiKey抓取access_tokenEndUser.joins(:account).joins(:api_key).find_by(access_token:'9b3322aff14d38046f32de9c79ed8273') 不要兴奋这不是生产

来自控制台的输出显示ActiveRecord::ConfigurationError: Association named 'api_key' was not found on EndUser; perhaps you misspelled it?但是api_key IS和帐户关联。如何告诉Rails我正在寻找它Account ApiKey EndUser而不是ApiKey {/ 1}}?

1 个答案:

答案 0 :(得分:2)

这些是嵌套连接,因此请将它们包含在joins的同一个调用中:

EndUser.joins(:account => :api_key).find_by(:api_keys => {:access_token => '9b3322aff14d38046f32de9c79ed8273'})