Rails 5,我可以构造一个范围来获取我的关系的字段吗?

In Rails 5, can I construct a scope to get fields of my relation?

我想从我的 Rails 5 应用程序中的一系列关系中导出一个字段(我想知道与球员相关的所有可能的统一颜色)。我有这些模型...

class Player < ApplicationRecord
    ...
    belongs_to :team, :optional => true


class Team < ApplicationRecord
    ...
    has_many :uniforms, :dependent => :destroy


class Uniform < ApplicationRecord
    ...
    has_many :colors, :dependent => :nullify

我想获取与Player模型关联的所有颜色,所以我构造了这个作用域...

class Player < ApplicationRecord
...
  scope :with_colors, lambda {
    joins(:team => { :uniforms => :resolutions })
  }

但是,当我构造一个对象并尝试在我的作用域中引用派生字段时,我得到一个方法未定义错误...

[12] pry(main)> p.with_colors
NoMethodError: undefined method `with_colors' for #<Player:0x00007fa5ab881f50>

访问字段的正确方法是什么?

模型应如下所示:

class Player < ApplicationRecord
    ...
    belongs_to :team, :optional => true


class Team < ApplicationRecord
    ...
    has_many :players
    has_many :colors, through: :uniforms
    has_many :uniforms, :dependent => :destroy


class Uniform < ApplicationRecord
    belongs_to :team
    has_many :colors, :dependent => :nullify

class Color < ApplicationRecord
    belongs_to :uniform

请注意团队 has_many :colors, through: :uniforms。这样你就可以调用 @player.team.colors 并获得球队制服的所有可用颜色。

有关 has_many through 的更多详细信息 https://guides.rubyonrails.org/association_basics.html#the-has-many-through-association