I modelli sono come questo:Come dovrei scrivere ActiveRecord quando ci sono più associazioni?
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
E sotto sono i dati:
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 |
| | |
e ora voglio trovare tutti i contratti che hanno stipulato con il cliente il nome di "Terry", in questo modo:
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
qualcuno mi ha detto che può funzionare in questo modo:
Contract.join(:customer).where("customers.name like '%terry%'").includes(:user,:buyer)
#It works fine.
Ho provato e funziona. Ma anche quando il modello Contract appartiene a un altro modello, come currency_id, il metodo sopra non può funzionare di nuovo.
Contract.join(:customer).where("customers.name like '%terry%'").includes(:currency, :user, :buyer)
#>>Mysql2::Error: Unknown column 'customers_contracts.id' in 'field list': ...
scusate, ho dimenticato di aggiungere la relazione del modello ... E il file di registro è di circa 40 o 50 linee perché la mia condizione attuale è molto complessa. Ero totalmente confuso da loro. – TerryChen