Marco
Marco

Reputation: 10823

Autoincrement text field in Rails 3.1

I'm new to rails and I hope you can help me. I'm creating an application to manage my warehouses. In my Transport Documents section I need a non-editable field that assigns an ID to any document, and I want this ID to increment automatically.

The ID is composed of a prefix (this changes based on the user loggged in) and an integer that must increment itself every time a user creates a transport document. An example will explain it better:

1) User "Mark" logged in application

First Transport Document ID:  MARK00001 
Second Transport Document ID: MARK00002

1) User "Peter" logged in application

First Transport Document ID:  PETE00001 
Second Transport Document ID: PETE00002

and so on. Any suggestions on how to do this?

Upvotes: 1

Views: 483

Answers (2)

thorsten müller
thorsten müller

Reputation: 5651

For a start I would get the highest value in a before_create filter and then generate a new number. The User model should have something like a prefix method to get the users prefix. Assuming that a TransportDocument belongs to a user I would do something like this:

class TransportDocument << ActiveRecord::Base
  before_create :set_per_user_id

  def document_id_txt
    "#{user.prefix}#{document_id}"
  end

  private
    def set_per_user_id
      val = user.transport_documents.maximum(:document_id)
      self.document_id = val + 1
    end
end

I didn't test the code but it should be roughly working like that. If you need to store the prefix in the field, it would become slightly more tedious to return the actual highest value.

Setting some validation on the document_id field to ensure uniqueness per user would be a good idea too.

Upvotes: 2

Marc Talbot
Marc Talbot

Reputation: 2059

You can hook into the before_create callback on your record:

class TransportDocument << ActiveRecord::Base
  before_create :set_friendly_id

  private
    def set_friendly_id
      # create your friendly_id here (hard to sample code without knowing your model)
      # friendly_id = current_user.name.upcase + number_of_records_plus_one_nice_format
      self.friendly_id = friendly_id
    end
end

If you need help assembling the friendly_name we'd need to know more about your model structure.

Upvotes: 2

Related Questions