1

ユーザー モデルを持つアプリを作成しています。このモデルのユーザーは、2 つの異なるユーザー タイプになる可能性があります。

user.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

user_id の代わりに 2 番目の forien_key でスコープを検索することは可能ですか?

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 に答える