has_one relationships don’t have id only getters or setters. For example engineer.laptop_id or engineer.laptop_id= are not implemented in Rails 5. Is there any reason for this?
class Engineer < ActiveRecord::Base
belongs_to :team
has_one :laptop
has_many :tasks
end
engineer = Engineer.first
Getters
engineer.team_id # works
engineer.laptop_id # doesnt work (Not implemented)
engineer.task_ids # work
No, because belongs_to is for when the foreign key lives on the record with the association and has_one is when the foreign key lives on the associated model instead.
Ypu can’t have the _id setter on the model with the association because there is no such field on the model or underlying table.
has_many relationship also has the foreign key in another table in the above example it would be in the tasks table. Regardless it has an accessor only for ids of related tasks engineer.task_ids.
Similarly, Shouldn’t has_one also have accessors for id even if its in another table?
But I think this is intentional… has_one associations are tricky and hard to “fit” into a novices mindset.
Having getters like .association_id would only make things more complicated when the programmer bangs their heads against the wall because .association_id = 123.