考慮兩種型號:不能確定「模型A屬於模型B」還是「模型B屬於模型A」?
User
=>(ID:整數,名稱:字符串,created_at:日期時間,的updated_at:日期時間,部門標識:整數)Department
=>(ID:整數,名稱:字符串,created_at:datetime,updated_at:datetime)
現在,這兩個表之間存在明顯的關係。它是
- 每個
User
有一個部門 - 一個
Department
屬於多個用戶,即有多個用戶在一個單一的部門
所以,我選擇了E按下下同爲A 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
&不A belongs to B
?
因爲沒有「belongs_to_many」?一個部門有很多用戶 - 我只是想到「belongs_to」作爲該關係的一個反向名稱。 –