ruby on rails - Creating has_one association within the same model -
let consider below model.
user{ id:number(primary_key), column1:string, column2:string)
now, column1 can string, column2 can either null, or have values column1. column1 , column2 can't same. i.e. column2 foreign key , reference column1.
how create has_one relationship these constraints.
something like,
has_one :master_agreement, :class_name => 'user', :foreign_key => 'column2', :primary_key => 'column1'
but above mentioned doesn't work me.
to setup self-joining relationship in rails want use belongs_to
not has_one
key difference belongs_to
places foreign key column on model's table - while has_one
places on other end.
class user < activerecord::base belongs_to :company # references users.company_id has_one :company # references companies.user_id end
lets consider system have 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 self joining relationship categories.parent_id
foreign key column references categories.id
.
while potentially use different categories.id
reference making things harder on id column indexed primary key column.
Comments
Post a Comment