我有以下模型:
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
作为普通方法。
这样您就不必更改代码库中的其他任何地方,并且只需进行最少的更改即可工作。
Read more here about alias_attribute
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
,我个人认为这样更明确。但缺点是,您必须更改代码中的更多位置。
关于ruby-on-rails - 覆盖 has_many getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58583918/