【问题标题】:Change model attribute in ActiveRecord in Ruby on Rails在 Ruby on Rails 中更改 ActiveRecord 中的模型属性
【发布时间】:2019-06-28 10:34:54
【问题描述】:
class Person < ActiveRecord::Base
  belongs_to :parent, class_name: 'Person'
  has_many :children, class_name: 'Person', foreign_key: :parent_id
  has_many :grandchildren, class_name: 'Person', through: :children, source: :children
end

我希望这个模型以这种方式工作(不管如何):

grandfather = Person.create(name: "Grandfather")
father = Person.create(name: "Father", parent: grandfather)
son = Person.create(name: "Son", parent: father)

grandfather.children.map(&:name)
=> ['father']
grandfather.grandchildren.map(&:name)
=> ['Son']

所以想法是让孩子的名字小写。我可以使用回调或覆盖 name 属性的 getter,但这适用于子孙,所以这不是重点。

【问题讨论】:

  • 首先,为什么不在你需要的地方明确地小写名称呢?好像是XY problem
  • @OleksiiFilonenko 我正在学习 Rails,它是练习的一部分,所以它不需要任何意义。

标签: ruby-on-rails ruby activerecord ruby-on-rails-5


【解决方案1】:

我猜这个任务是添加关于记录是“儿子”而不是“孙子”的知识。所以你有一个有向树,并且需要知道每个节点的深度:

class Person < ActiveRecord::Base
...
  def depth
    (parent&.depth || 0) + 1
  end

  def name
    if depth == 2
      super.downcase
    else
      super
    end
  end
end

请注意,这对于具有深度嵌套的大型数据结构效率不高,最好将其具体化为应在设置父级时计算的附加属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多