Skip to content

Instantly share code, notes, and snippets.

@Linell
Created September 4, 2019 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Linell/5f8bae28b8b93a9c2a3bf4b58ed27a86 to your computer and use it in GitHub Desktop.
Save Linell/5f8bae28b8b93a9c2a3bf4b58ed27a86 to your computer and use it in GitHub Desktop.
Is there a better version of this code?
# Original code. The problem here is that if there's an existing
# Bar object for the user then we end up with two objects. That's
# a valid case though -- we just don't want it here. I want it to
# result in the user having one confirmed Bar object.
foo = Bar.create_or_raise(
user: user,
entity: entity,
status: :confirmed,
role: :owner
)
# The following accomplishes that by trying to find a bar object
# for the user/entity combo before creation. *BUT* it seems like
# there is a better way to do the find/update.
foo = Bar.find_or_create_by!(user: user, entity: entity)
foo.update(status: :confirmed, role: :owner)
# Is there a better, or at least cleaner looking, way to do this?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment