这是我的 ActiveRecord 模型,带有 Rails 3.2:
class User < ActiveRecord::Base
has_one :criterion
has_many :user_offer_choices
end
class Offer < ActiveRecord::Base
has_many :user_offer_choices
def seen
user_offer_choices.where(seen: true)
end
def accepted
user_offer_choices.where(accepted: true)
end
end
class Criterion < ActiveRecord::Base
belongs_to :user
end
class UserOfferChoice < ActiveRecord::Base
belongs_to :user
belongs_to :offer
end
我想获得看到报价的用户的所有标准。就像是 :
Offer.find(11).seen.users.criterions
但我不知道如何使用 ActiveRecord
我知道我可以做类似的事情:
Criterion.joins(user: { user_offer_choices: :offer }).where(user: { user_offer_choices: {accepted: true, offer_id: 11} } )
但我希望能够在报价中使用我的范围(已查看并已接受)。那么我该怎么做呢?
编辑: 我找到了我想要的,Arel 的合并方法:http: //benhoskin.gs/2012/07/04/arel-merge-a-hidden-gem