我正在用 Ruby on Rails 创建一个站点,我有两个模型,一个是 User
模型,一个是 Transaction
模型。
这些模型都属于一个帐户,因此它们都有一个名为 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)
干杯
头皮
最佳答案
class Account < ActiveRecord::Base
has_many :users
has_many :transactions
end
class User < ActiveRecord::Base
has_many :transactions, :through => :account
end
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001833
关于ruby-on-rails - Ruby on Rails - 主键和外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2801900/