【问题标题】:Scope records a user has purchased用户购买的范围记录
【发布时间】:2018-09-03 00:05:49
【问题描述】:

这是我的设置:

  • 用户有很多购买
  • 包有很多购买
  • 包有很多食谱

我想选择用户在Recipe 类中购买的所有食谱。这是我现在所拥有的:

scope :purchased, lambda { |user| includes(pack: :purchases).where(packs: { purchases: { user: user } }) }

由于某种原因,当我调用 Recipe.purchased(current_user) 时,我得到了所有 Recipe 记录。

我在使用范围时做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord scope associations


    【解决方案1】:

    这可以在 Rails 中轻松完成。您只需将has_many:through 选项一起使用,如下所示:

    class User < ApplicationRecord
      has_many :purchases
      has_many :packs, through: :purchases
      has_many :recipes, through: :packs
    end
    
    user = User.first
    user.recipes # returns all user's recipes
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-18
      • 2017-10-03
      • 1970-01-01
      • 2018-02-24
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多