【问题标题】:Rails: How to combine association and scopeRails:如何结合关联和范围
【发布时间】:2015-11-07 17:34:52
【问题描述】:

我想为特定用户获取“offer”类型的所有 TaskInteractions。

我有一个用户模型

has_many :task_interactions

和一个 TaskInteraction 模型

belongs_to :user

TaskInteraction 有一个属性“type”,它的值可以是 offer 或 quiz。

目前,我正在使用范围

scope :offer_interactions, -> { where(type: 'offer') }

我得到了结果

@user.task_interactions.offer_interactions

或者在我可以定义的用户模型中:

def offer_interactions
  self.task_interactions.where(type: 'offer')
end

或者如果我将范围和 offer_interactions 方法结合起来:

def offer_interactions
  self.task_interactions.offer_interactions
end

问题:

有没有更好的方法来获得这个结果?

Rails 有办法解决这个问题吗?

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    您还可以在 User 模型中添加一个作用域has_many 关系,以仅考虑报价任务交互:

    has_many :offer_interactions, -> { where(type: 'offer') }, class_name: 'TaskInteraction'

    然后拨打@user.offer_interactions

    【讨论】:

    • 谢谢,这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2016-07-23
    • 2013-06-09
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2020-10-11
    相关资源
    最近更新 更多