首页 > 解决方案 > 根据条件定义 getter 的返回

问题描述

我想根据 Ruby on Rails 5 中的条件更改 getter 方法返回的内容。

我有:

class Foo < ApplicationRecord
  # has an boolean attribute :my_boolean
  has_many :bars, through: :FooBar, dependent: :destroy
end

class Bar < ApplicationRecord
  has_many :foos, through: :FooBar, dependent: :destroy
  scope :my_scope, -> {where(some_attribute: true)}
end

class FooBar < ApplicationRecord
  belongs_to :Foo
  belongs_to :Bar
end

我希望如果 Foo 必须:my_booleantrue当我调用foo.bars它时,它会在范围内返回他的酒吧:my_scope,否则它会返回他的所有酒吧。

我试图覆盖Bargetter但没有成功,例如:

class Foo < ApplicationRecord
  ...

  def bars
    bars = self.bars
    return bars.my_scope if self.my_boolean
    bars
  end
end

有什么想法可以完成这项工作吗?

标签: ruby-on-railsmodelscopegetterhas-many-through

解决方案


您不能has_many以相同的方式命名您的方法和您的方法而不会出现stack level too deep异常(我想您在代码中打错了,应该是has_many :bars,带有“s”)。

你可以做的是:

def my_boolean_bars
  return bars unless my_boolean

  bars.my_scope
end

或者使用与您实施的相同的方法,这对我来说似乎没问题。

编辑:

如果要保留方法名称,可以执行以下操作:

class Foo < ApplicationRecord
  has_many :bars, through: :FooBar, dependent: :destroy

  alias_method :ori_bars, :bars

  def bars
    return ori_bars unless my_boolean
    
    ori_bars.my_scope
  end
end

推荐阅读