如何在 Rails 5.2 上的 Ruby 中为多态关系的 belongs_to 声明创建别名?
How to create an alias in a belongs_to declaration for a polymorphic relation in Ruby on Rails 5.2?
我的应用程序中的几个对象属于具有这种关系的父对象:
belongs_to :parent, :class_name => "Playground", :foreign_key => "playground_id"
我使用 :parent 声明,因为这允许我创建一个用于构建面包屑的助手:
def breadcrumbs(object)
way_back = [object]
while object.parent.class != Playground do # stop when comes to display the Playground
path = object.parent
way_back << path
object = path
end
puts way_back.reverse
way_back.reverse
end
多态的 BusinessObject class 变得更加复杂。业务对象属于业务流程或业务领域。关系定义如下:
# The parent relationship points to either Business Area or Business Process and relies on
# area_process_type :string
# area_process_id :integer
belongs_to :area_process, polymorphic: true
因此,我如何定义此 belongs_to :area_process 关系的别名,以便将其用作 :parent 其他地方?
是否有声明别名 belongs_to 子句的语法,或者我应该为业务对象创建一个名为 "parent" 的方法来解决这个问题?
附录 - 父方法可能是这个:
### define the parent of current business object
def parent
parent_class = self.area_process_type.constantize
parent_class.find(self.area_process_id)
end
非常感谢。
您可以通过将以下内容添加到您的 BusinessObject
模型来使用 alias_attribute
:
alias_attribute :parent, :area_process
我的应用程序中的几个对象属于具有这种关系的父对象:
belongs_to :parent, :class_name => "Playground", :foreign_key => "playground_id"
我使用 :parent 声明,因为这允许我创建一个用于构建面包屑的助手:
def breadcrumbs(object)
way_back = [object]
while object.parent.class != Playground do # stop when comes to display the Playground
path = object.parent
way_back << path
object = path
end
puts way_back.reverse
way_back.reverse
end
多态的 BusinessObject class 变得更加复杂。业务对象属于业务流程或业务领域。关系定义如下:
# The parent relationship points to either Business Area or Business Process and relies on
# area_process_type :string
# area_process_id :integer
belongs_to :area_process, polymorphic: true
因此,我如何定义此 belongs_to :area_process 关系的别名,以便将其用作 :parent 其他地方? 是否有声明别名 belongs_to 子句的语法,或者我应该为业务对象创建一个名为 "parent" 的方法来解决这个问题?
附录 - 父方法可能是这个:
### define the parent of current business object
def parent
parent_class = self.area_process_type.constantize
parent_class.find(self.area_process_id)
end
非常感谢。
您可以通过将以下内容添加到您的 BusinessObject
模型来使用 alias_attribute
:
alias_attribute :parent, :area_process