find_or_create_by_
does exactly what it says: it either creates a new item (create saves to database) or finds the existing one, meaning reads it from the database.
It returns false on validation errors when creating an object
So to save changes you use the normal update methods:
if @college= College.find_or_create_by_name(given_attributes) &&
@college.update_attributes(given_attributes)
else
# handle validation errors
end
It won't hit the database twice, because update_attributes
does'n apply any changes to newly created objects (but possible changes to existing ones)
To write it more explicit:
@college= College.find_or_create_by_name(given_attributes)
if @college.present?
if @college.update_attributes(given_attributes)
# do your success stuff
else
# handle update validation errors
end
else
# handle find_or_create errors
end