[英]looking up value of self-join column in Rails
I'm pretty rusty working on Rails, so I apologize if this is a noob question. 我在Rails上工作时非常生锈,所以如果这是一个菜鸟问题,我深表歉意。
I have a table called "Customer", which has a column called "parent_customer_id", which is a self-referential column looking at the id column in the same table 我有一个名为“ Customer”的表,该表具有一个名为“ parent_customer_id”的列,这是一个自引用列,用于查看同一表中的id列
how do i design the model and view files (not clear on how to write the lookup code in the view) so that, in the view, i can show data in this format: 我如何设计模型和查看文件(不清楚如何在视图中编写查找代码),以便在视图中可以显示以下格式的数据:
Customer Name: @customer_name (Parent Customer Name: @parent_customer_name) 客户名称:@customer_name(父客户名称:@parent_customer_name)
So in your Customer model, you'll have 因此,在您的客户模型中,您将拥有
belongs_to :parent_customer, class: Customer
has_many :child_customers, class: Customer,
foreign_key: "parent_customer_id"
And in your view, you'll have something like this: 在您看来,您将获得以下内容:
Customer Name: <%= @customer.name %> (Parent customer name:
<%= @customer.parent_customer.try "name" %>)
Use "try" so that Rails doesn't throw an exception if there's no parent customer. 使用“ try”,以便在没有父客户的情况下,Rails不会引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.