考虑两个模型:
User
=>(id:整数,名称:字符串,created_at:日期时间,updated_at:日期时间,department_id:整数)Department
=>(id:整数,名称:字符串,created_at:日期时间,updated_at:日期时间)
现在,这两个表之间有明显的关系。这是
- 每个
User
部门都有一个部门 - A
Department
属于多个用户,即一个部门有多个用户
所以,我选择了与以下相同的epressA belongs_to B
class User < ActiveRecord::Base
has_one :department
end
class Department < ActiveRecord::Base
belongs_to :user
end
但您可能知道这不起作用并引发以下错误:
> @user = User.find(1)
> @user.department.name
Department Load (1.0ms) SELECT "departments".* FROM "departments" WHERE "departments"."user_id" = 1 LIMIT 1
ActiveRecord::StatementInvalid: PG::Error: ERROR: column departments.user_id does not exist
经过大量的打击和试验。我偶然发现了定义这个的正确方法,这只是另一种方式,即B belongs to A
class Department < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
belongs_to :department
end
> @user = User.find(1)
> @user.department.name
Department Load (1.0ms) SELECT "departments".* FROM "departments" WHERE "departments"."id" = 1 LIMIT 1
=> "HR"
现在,这与我的大脑对这些关联的看法完全相反。所以,我有点困惑,所以如果有人能解释发生了什么?
为什么B belongs to A
& NOT A belongs to B
?