Skip to content

Instantly share code, notes, and snippets.

@JamesChevalier
Created October 7, 2016 15:13
Show Gist options
  • Save JamesChevalier/aadd5fd35a5bc2c0641fb5bf6d1f4967 to your computer and use it in GitHub Desktop.
Save JamesChevalier/aadd5fd35a5bc2c0641fb5bf6d1f4967 to your computer and use it in GitHub Desktop.
Caveat with making strict has_one relations in Rails

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_id validation on the Item model
  • 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment