在Ruby on Rails中的ActiveRecord中更改模型属性

时间:2019-06-28 10:34:54

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

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,但这适用于子代和子代,所以这不是重点。

1 个答案:

答案 0 :(得分:1)

我可以猜到,这是在增加关于记录是“儿子”而不是“孙子”的知识。因此,您有一棵定向树,并且需要知道每个节点的深度:

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

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

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