我在Ruby on Rails中創建站點,我有兩個模型User
模型和Transaction
模型。Ruby on Rails - 主鍵和外鍵
這些模型都屬於一個帳戶,以便它們都具有一個名爲場account_id
我試圖建立它們之間的關聯,像這樣:
class User < ActiveRecord::Base
belongs_to :account
has_many :transactions
end
class Transaction < ActiveRecord::Base
belongs_to :account
belongs_to :user
end
我使用這些協會,如下所示:
user = User.find(1)
transactions = user.transactions
目前的應用程序試圖找到與user_id
的交易,這裏是它生成的SQL:
Mysql::Error: Unknown column 'transactions.user_id' in 'where clause': SELECT * FROM `transactions` WHERE (`transactions`.user_id = 1)
這是不正確的,我想通過account_id
中找到交易,我已經嘗試設置像這樣的關聯:
class User < ActiveRecord::Base
belongs_to :account
has_many :transactions, :primary_key => :account_id, :class_name => "Transaction"
end
class Transaction < ActiveRecord::Base
belongs_to :account
belongs_to :user, :foreign_key => :account_id, :class_name => "User"
end
這幾乎達到我所希望做的,併產生下面的SQL:
Mysql::Error: Unknown column 'transactions.user_id' in 'where clause': SELECT * FROM `transactions` WHERE (`transactions`.user_id = 104)
數量104
是正確account_id
,但它仍試圖查詢交易表爲user_id
字段。可能有人給我上的關聯如何我設置查詢事務表爲account_id
而不是user_id
導致SQL查詢,像這樣一些建議:
SELECT * FROM `transactions` WHERE (`transactions`.account_id = 104)
乾杯
EEF
你應該合理適當語法高亮和縮進構建答案數據。 – RatDon 2015-03-20 05:31:06