我正在编写一个具有用户模型的应用程序,该模型中的用户可以是两种不同的用户类型。
用户.rb
class User < ActiveRecord::Base
has_many :transactions
has_many :transaction_details, :through => :transactions
has_many :renters, :class_name => "Transactions"
end
事务.rb
class Transaction < ActiveRecord::Base
has_many :transaction_details
belongs_to :user
belongs_to :renter, :class_name => "User"
end
transaction_detail.rb
class TransactionDetail < ActiveRecord::Base
belongs_to :transaction
belongs_to :inventory
scope :all_open, where("transaction_details.checked_in_at is null")
scope :all_closed, where("transaction_details.checked_in_at is not null")
end
基本上,用户可能是租客,也可能是签出物品的人。完成交易后,我可以致电:
@transaction.renter.first_name # receive the first name of the renter from the renter table
@transaction.user.first_name # receive the first name of user who performed the transaction
这是完美的,正如我所料。对于我的生活,我无法弄清楚如何在通过用户调用时使范围工作:
# trying to perform the scrope "all_open", limted to the current user record, but I cant get it to use the
# renter_id column instead of the user_id column
u.transaction_details.all_open
这是否可以通过第二个 forien_key 而不是 user_id 进行 scrope 查找?