【问题标题】:Rails 3 Multiple Foreign KeysRails 3 多个外键
【发布时间】:2023-03-30 12:56:01
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    在 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
    

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 2011-08-31
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      相关资源
      最近更新 更多