-
Get a monthly update on best practices for delivering successful software.
Have you often run into a situation where you have a hash full of properties and you want to either create a new ActiveRecord object (if it doesn't exist) or update one (if it exists)?
For example,
class User
# has properties: ssn, first_name, :last_name, :age, :email, :password
def create_or_update_by_ssn(params)
user = Disease.find_by_ssn(params[:ssn])
if user.nil?
user = User.create(params)
else
user.update_attributes!(params)
end
end
end
Here, the business rule states that a user's SSN is unique, so called natural-key.
If we can identify what constitutes a natural-key for each model object in our domain-model, when we could DRY out this functionality.
Topics: activerecord, natural key, primary key, rails, ruby, surrogate key