[英]Creating has_one association within the same model
Let us consider the below model. 让我们考虑以下模型。
User{ id:number(primary_key), column1:string, column2:string)
Now, the column1 can be any string, but column2 can be either null, or have values from column1. 现在,column1可以是任何字符串,但是column2可以为null,也可以具有column1中的值。 However column1 and column2 can't be same.
但是column1和column2不能相同。 IE column2 will be the foreign key and it will reference column1.
IE column2将是外键,它将引用column1。
How will i create a has_one relationship with these constraints. 我将如何创建具有这些约束的has_one关系。
Something like, 就像是,
has_one :master_agreement, :class_name => 'User', :foreign_key => 'column2', :primary_key => 'column1'
but the above mentioned doesn't work for me. 但是上述内容对我不起作用。
To setup a self-joining relationship in rails you want to use belongs_to
not has_one
as the key difference is that belongs_to
places the foreign key column on the model's table - while has_one
places it on the other end. 要设置在轨自加盟关系,要使用
belongs_to
不has_one
的关键区别是belongs_to
模型上的表的外键列的地方-而has_one
其放在另一端。
class User < ActiveRecord::Base
belongs_to :company # references users.company_id
has_one :company # references companies.user_id
end
Lets consider a system where you have a hierarchy of categories: 让我们考虑一个具有类别层次结构的系统:
class Category < ActiveRecord::Base
belongs_to :parent, class_name: 'Category'
has_many :subcategories, class_name: 'Category', foreign_key: 'parent_id'
end
This creates a self joining relationship with the categories.parent_id
foreign key column which references categories.id
. 这将创建一个与
categories.parent_id
外键列的自连接关系,该外键列引用categories.id
。
While you could potentially use something different than categories.id
as the reference you are just making things harder on yourself as the id column already is an indexed primary key column. 虽然您可能会使用不同于
categories.id
作为参考,但由于id列已经是索引主键列,因此使您的工作变得更加困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.