ActiveRecord has_one relationship shouldn't this be supported? Happy to make a pull request if yes

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

Same issue with setters too.

``

Thanks

Shishir

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.

That is because there is no laptop_id in Engineer (assuming engineer
has_one laptop). Laptop has an engineer_id. You can do
engineer.laptop.id

Colin

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?

I think it makes sense. Note that there are a whole other methods that exist on has_many relations that do not have equivalent on has_one:

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.