繁体   English   中英

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

[英]Change model attribute in ActiveRecord in Ruby on Rails

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM