ruby-on-rails - 覆盖 has_many getter

标签 ruby-on-rails ruby

我有以下模型:

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/

相关文章:

ruby-on-rails - Ruby on Rails - 如何在创建时处理 belongs_to 多个

ruby-on-rails - rails 复位单柱

sql - rails 参与!错误(无法批量分配 protected 属性 : user)

Ruby popen 和可执行路径?

ruby-on-rails - 为什么 'logger.debug false' 不打印任何东西?

ruby-on-rails - rake spec 在 specs 之后运行测试

ruby-on-rails - Rails redirect_to Ruby 2.2/Rails 4.2 的新行为?

ruby-on-rails - 用户匹配系统,高效的搜索方式?

javascript - 部署到生产时设置开发环境标志并消除调试代码

ruby - 如何在循环中获取字符串对象名称?