当存在多个关联时,我应该如何编写ActiveRecord?

Ter*_*hen 5 activerecord associations ruby-on-rails-3

模型是这样的:

class Contract < ActiveRecord::Base  
  belongs_to :buyer, :class_name => 'Customer', :foreign_key => 'buyer_customer_id' 
  belongs_to :user, :class_name => 'Customer', :foreign_key => 'user_customer_id'
  belongs_to :currency
end  

class Customer < ActiveRecord::Base  
  has_many :as_buyer_in_contracts, :class_name => 'Contract', :foreign_key => 'buyer_customer_id'  
  has_many :as_user_in_contracts, :class_name => 'Contract',:foreign_key => 'user_customer_id'  
end

class Currency < ActiveRecord::Base
  has_many :contracts
end
Run Code Online (Sandbox Code Playgroud)

以下是数据:

Contract
+----+-------------------+------------------+-------------+
| id | buyer_customer_id | user_customer_id | currency_id |
+----+-------------------+------------------+-------------+
|  1 |         1         |        3         |      3      |
|  2 |         2         |        2         |      2      |
|  3 |         2         |        1         |      2      |
|    |                   |                  |             |


Customer
+----+-------------------+
| id |       name        |
+----+-------------------+
|  1 |    Terry Brown    |
|  2 |    Tom Green      |
|  3 |    Kate White     |
|    |                   |

Currency
+----+-------------------+
| id |       name        |
+----+-------------------+
|  1 |        EUR        |
|  2 |        USD        |
|  3 |        JPY        |
|    |                   |
Run Code Online (Sandbox Code Playgroud)

现在我想找到所有与客户签名的合同"Terry",如下所示:

Contract.where("customers.name like '%Terry%'").includes(:buyer,:user)
#I want 1 and 3, but it can only get 1
Contract.where("customers.name like '%Terry%'").includes(:user, :buyer)
#If I write "user" before "buyer", then I can only get 3
Run Code Online (Sandbox Code Playgroud)

有人告诉我它可以像这样工作:

Contract.join(:customer).where("customers.name like '%terry%'").includes(:user,:buyer)
#It works fine.
Run Code Online (Sandbox Code Playgroud)

我试过,它确实有效.但是当合同模型属于其他模型(例如currency_id)时,上述方法不能再次起作用.

Contract.join(:customer).where("customers.name like '%terry%'").includes(:currency, :user, :buyer)
#>>Mysql2::Error: Unknown column 'customers_contracts.id' in 'field list': ...
Run Code Online (Sandbox Code Playgroud)

hou*_*se9 0

您是否尝试过使用连接 :buyer 或 :user 而不是 :customer ?

您的合同模型没有:客户属性/关系

Contract.join(:buyer).where("customers.name like '%terry%'").includes(:currency, :user, :buyer)
Run Code Online (Sandbox Code Playgroud)

我的猜测是这相当于

Contract.join("INNER JOIN customers ON customers.id = contracts.buyer_customer_id").where("customers.name like '%terry%'").includes(:currency, :user, :buyer)
Run Code Online (Sandbox Code Playgroud)

检查日志文件以准确查看每种情况下生成的 sql - log/development.log