开发者

Rails custom serial number restarting each year

I have a need for a custom serial number in the format U2011-001 and so on and so forth where 2011 is the year and each year it has to start over, I thought about using the id to gene开发者_开发技巧rate it when it came out but that just keeps going up...I need this to restart each year.


I think you can use an after create hook to populate your serial number if you absolutely have to.

after_create :set_serial_number

def set_serial_number
  serial_number = "U#{created_at.year}-#{id}"
end

Otherwise, you if you don't need to persist this, you can just use a method to populate the serial number field this way:

def serial_number
  "U#{created_at.year}-#{id}"
end


def last_serial_number
  @last_serial_number ||= YourModel.select(:serial_number).
                            where('serial_number LIKE "U' + Time.new.year + '-%"').
                            order("serial_number DESC").first
end

def last_serial_sub_part
  last_serial_number.split('-').last
end

def next_serial
  last_serial_number.nil? ?
    generate_serial_number :
    generate_serial_number(last_serial_sub_part.succ)
end

def generate_serial_number(sub_part='000')
  "U#{Time.new.year}-#{sub_part}"
end

Something like this could work. It's off the top of my head, so it's quite sloppy. You could set your serial number field to the value returned by next_serial in a before_validation callback. I'd also highly recommend making most of these methods private.


I made a table that stored the value and did 2 SQL queries one to find the last updated time check if it is a new year if so restart the number.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜