Let's say you have a User with this relation:
has_one :item
The has_one relation disallows you from doing this:
first_user = User.first
first_user.item.create(field_one: value, field_two: value)
You can do this, though:
first_user.create_item(field_one: value, field_two: value)
However
If the User already has one Item, then the first_user.create_item call will delete the other Item (and its relational data if cascades are in place) and create a new one.
If you have a validation on the Item to validate uniqueness of the user_id field, the first_user.create_item call will delete the other Item.
Also, according to this comment, using build_association will clear the foreign key in the database which will disconnect the two relations.
If you need a strict has_one relation, then I'd recommend never using the first_user.create_item method & instead:
- add a
validates_uniqueness_of :user_idvalidation on theItemmodel - always create that object directly via
Item.create(user_id: 1)
Another way through this is covered in this StackOverflow post which suggests checking for the presence of the Item before taking action.