Topic: surrogate key

ActiveRecord create_or_update based on natural-key

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.

Continue reading »

Launch: Pathfinder Newsletter

    Get a monthly update on best practices for delivering successful software.

    Subscribe via email


    Subscribe via RSS      RSS icon

Topics

Search

WordPress

Comments about this site: info@pathf.com