我在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