在Rails 5中,我可以构造一个作用域来获取我的关系字段吗?

问题描述 投票:1回答:1

我想从我的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>

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

ruby-on-rails scope ruby-on-rails-5 finder
1个回答
0
投票

模型应该看起来像:

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的更多详细信息>

© www.soinside.com 2019 - 2024. All rights reserved.