Rails 3多个外键

时间:2012-08-06 05:10:23

标签: ruby-on-rails ruby-on-rails-3 scope

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

user.rb

class User < ActiveRecord::Base
  has_many        :transactions
  has_many        :transaction_details, :through => :transactions
  has_many        :renters, :class_name => "Transactions"
end

transaction.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?

1 个答案:

答案 0 :(得分:0)

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

您需要提及反向关联定义中使用的foriegn密钥。

在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