ruby-on-rails - 根据条件定义 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_boolean
,true
当我调用foo.bars
它时,它会在范围内返回他的酒吧:my_scope
,否则它会返回他的所有酒吧。
我试图覆盖Bar
getter但没有成功,例如:
class Foo < ApplicationRecord
...
def bars
bars = self.bars
return bars.my_scope if self.my_boolean
bars
end
end
有什么想法可以完成这项工作吗?
解决方案
您不能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
推荐阅读
- nginx - nginx -- 连接到上游时没有实时上游
- c++ - 无法将函数指针作为函数参数传递
- sql - 授予通过 database_link 选择同义词
- flutter - Dart/Flutter 中 BLoC 模式的最佳实践
- c# - 我应该如何在我的项目中引用一个文件,所以当我发布应用程序时,该文件是在特定文件夹中生成的?
- python - 具有相同架构的 Keras 和 Pytorch 代码之间的区别
- notepad++ - Notepad++ 正则表达式 [^az] 未返回预期的匹配项
- python - Arduino 和树莓派 4 之间的蓝牙通信
- sql - 使用多个 with 优化慢查询
- airflow - 如何在 Airflow 中使用 last_mod_dt(时间戳)从 oracle 数据源中执行每小时增量提取?