ruby-on-rails - 覆盖 has_many getter
问题描述
我有以下模型:
class Metric < ApplicationRecord
has_many key_phrases
end
我想创建一个覆盖 getter 的方法,key_phrases
例如:
class Metric < ApplicationRecord
has_many key_phrases
def key_phrases
# if current value is not an empty array, return, otherwise creates, something like:
current_value = super()
return current_value unless current_value.nil?
get_key_phrases.each do |k|
key_phrases.create(k)
end
return key_phrases
end
end
我知道我想做什么,但是因为我缺乏关于 Ruby 和 Rails 的知识,所以我不知道如何编写代码。
解决方案
从技术上讲,您可以添加别名以确保其余代码不会中断。这个想法是将现有has_many
方法重命名为其他方法 并将现有方法key_phrases
用作普通方法。
这样您就不必更改代码库中的其他任何地方,并且只需进行最少的更改。
class Metric < ApplicationRecord
alias_attribute :phrases, :key_phrases #NOTE the alias_attribute should be before `key_phrases`
has_many key_phrases
def key_phrases
# your logic goes into this method
if phrases.empty?
# create
else
phrases
end
end
end
但是......我个人创建了一个更有意义的完整方法并保留“has_many key_phrases”,原因是,这意味着并获取,如果您尝试以相同的方法创建记录,这有点令人困惑。
所以,我会做这样的事情
class Metric < ApplicationRecord
has_many key_phrases
def get_or_create_key_phrases(*params)
if phrases.empty?
# create
else
phrases
end
end
end
然后更改所有调用的地方,key_phrases
我get_or_create_key_phrases
个人认为更明确。但不利的一面是,您必须更改代码中的更多位置。
推荐阅读
- magento2 - 如何编辑目录产品视图?
- reactjs - Redux + React Native 将产品添加到购物车不起作用
- python - 在图像中拟合多边形并找到角度
- reactjs - Gatsby TypeError - 无法读取未定义的属性“id”
- javascript - JavaScript - 循环后我无法保存变量的值
- android - 如何关联sqlite数据库中的多个表?
- python - Raspberry Pi - Raspbian Lite - Waveshare 2.8 英寸显示器 - Openbox/nodm - Tkinter 显示错误
- sql - 在 postgres 10.6 中禁用约束
- django - 如何修复 GeoDjango 教程?
- database - Flutter:存储简单数据的最有效选择