Consider the two models:
User=> (id: integer, name: string, created_at: datetime, updated_at: datetime, department_id: integer)Department=> (id: integer, name: string, created_at: datetime, updated_at: datetime)
Now, there is a obvious relationship between these two tables. it is
- Each
Userhas one department - A
Departmentbelongs to many users i.e there are multiple users in a single department
so, I chose epress the same as following as A belongs_to B
class User < ActiveRecord::Base
has_one :department
end
class Department < ActiveRecord::Base
belongs_to :user
end
But as you may know doesn’t work & throws the following error:
> @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
After lot of hit & trial. I stumbled on the correct way to define this, which is just other way around i.e 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"
Now, this is exact opposite of the way my brain thinks about these associations. So, I am little confused, so if anyone could explain what is going on?
Why does B belongs to A & NOT A belongs to B?
The
:has_onerelation is a little bit strange at the first look. Consider a user and an account, every account is connected to (belongs to) just one user, from the other side a user has_one account, just one, his account. An account is something that the user owns.In these cases you use the
has_onerelation on theUsermodel and Rails will search for auser_idcolumn in theaccountstable (see the has_one documentation in the Rails Guide).In your specific case I think is perfecty right to say “a department has many users” and “a user belongs to a department”.