我有以下代码:
class Item < ActiveRecord::Base
belongs_to :user
has_many :transactions
#scope :active, lambda??
end
class Transaction < ActiveRecord::Base
belongs_to :user
belongs_to :item
scope :active, where("status = 0")
end
class User < ActiveRecord::Base
has_many :items
has_many :transactions
end
我希望在模型Item中构建一个范围,以仅检索具有活动事务的记录,例如:
User.find(1).items.active
答案 0 :(得分:3)
我找到了答案。它应该是这样的:
scope :active, joins(:transactions)
Transaction.active
答案在这里:http://asciicasts.com/episodes/215-advanced-queries-in-rails-3