2013-06-13 1 views
0

У меня есть три модели: User, Product и Transaction.Пользовательский метод или ассоциация для ассоциативных ассоциаций моделей

Вот ассоциации:

приложение/модели/transaction.rb

# A transaction has a `current` boolean that is true when the transaction is currently happening, and nil else. 

belongs_to :seeker, class_name: "User", foreign_key: "seeker_id" 
belongs_to :product 

приложение/модели/user.rb

has_many :owned_products, class_name: "Product", 
          foreign_key: "owner_id", 
          dependent: :destroy 
has_many :transactions, foreign_key: "seeker_id", 
         dependent: :destroy 
has_many :requested_products, through: :transactions, source: :product 
has_many :active_transactions, -> { where current: true }, 
           class_name: 'Transaction', 
           foreign_key: "seeker_id" 
has_many :borrowed_products, through: :active_transactions, source: :product 

приложение/модели/product.rb

belongs_to :owner, class_name: "User", 
        foreign_key: "owner_id" 
has_many :transactions, dependent: :destroy 
has_many :seekers, through: :transactions, 
        source: :seeker 
has_one :active_transaction, -> { where current: true }, 
          class_name: 'Transaction' 
has_one :borrower, through: :active_transaction, 
          source: :seeker 

Я хочу создать метод, который позволяет мне сделать следующее:

user.owned_products.available # returns every product owned by the user that has a transaction with current:true. 
user.owned_products.lended # returns every product owned by the user that has no transaction with current.true 

Возможно ли это? Если нет, то я бы сделать ссылку ассоциации как user.available_products и user.lended_products, но я не знаю как, потому что я должен использовать условия обеих моделей для того, чтобы сделать ассоциацию в-третьих, как это:

приложение/модели /user.rb

has_many :available_products, -> { where borrower: nil }, 
           class_name: "Product", 
           foreign_key: "owner_id" 

И я получаю сообщение об ошибке:

ActionView::Template::Error: 
    SQLite3::SQLException: no such column: products.borrower: SELECT COUNT(*) FROM "products" WHERE "products"."owner_id" = ? AND "products"."borrower" IS NULL 

Любой намек?

ответ

0

Создание области

scope :available, where(:current => true).joins(:transactions) 

теперь вы можете сказать

user.owned_products.available 

Это не проверено. Но это даст вам представление о том, как идти вперед.

Here является ссылкой для областей.

+0

Спасибо. Извините, но это не работает :-( Я уже прочитал руководство по направляющим по областям, но примеров мало, и я не очень хорошо понимаю. В противном случае, как вы думаете, я должен удалить некоторые из моих 'has_many', чтобы заменить их на' scopes'? –