1

我正在编写一个具有用户模型的应用程序,该模型中的用户可以是两种不同的用户类型。

用户.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 查找?

4

1 回答 1

0

简短的回答 - 是的。这是很有可能的。

您需要提及反向关联定义中使用的外键。

在 users.rb 中:

has_many :rents, :class_name => "Transactions", :foreign_key => "renter_id"

这将允许您编写:

User.find(5).rents # array of transactions where user was renter

如果您想直接调用 transaction_details,那么您需要再次在 user.rb 中指定另一个关联:

has_many :rent_transaction_details, :through => :rents, :source => "TranactionDetail"

这将允许您致电:

User.find(5).rent_transaction_details.all_open
于 2012-09-21T12:07:21.173 回答