Is there a method to save an object but return the object if it fails the validation_uniqueness_of for a given field? For example, I have the following:
class User
has_many :words
...
end
class Word
belongs_to :user
validates_uniqueness_of :title
...
end
And I have a situation where I want to either return the Word object if the user has already saved this word, or return the newly saved word object. I am finding myself checking if the word object exists through my own search and then performing a save if not:
existing_word = find_by_word_and_user_id(word, user)
!existing_word.nil? ? existing_word : user.words.create({:word => word})
But I feel like if the user does not have the word saved, rails is going to perform a redundant search for the title uniqueness validation after my check and I was wondering if I could just do the save and return the already existing object that rails finds for the validation.