Models are as follows:
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
And below is the data:
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 |
| | |
And now I want to find all the contracts signed with the client under the name "Terry", for example:
Contract.where("customers.name like '%Terry%'").includes(:buyer,:user)
Contract.where("customers.name like '%Terry%'").includes(:user, :buyer)
Someone told me that it can work as follows:
Contract.join(:customer).where("customers.name like '%terry%'").includes(:user,:buyer)
I tried and it works. But if the model of the Contract belongs to another model, for example currency_id, the method above cannot work again.
Contract.join(:customer).where("customers.name like '%terry%'").includes(:currency, :user, :buyer)
source
share