Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: auto increment column with scope

I have projects and issues. The issue number (not ID) must be auto-increment but scoped with project_id. Any gem or easy way to accomplish that? Thank you!

Edit: acts_as_list will do the job, but what if a record is deleted? The next issue will be with it's number.

like image 880
7elephant Avatar asked Jan 13 '12 07:01

7elephant


1 Answers

in your Issue class:

belongs_to :project
before_validation( :on => :create ) do 
  self.issue_number = self.project.issues.collect { | issue | issue.issue_number }.max + 1
end

(or thereabouts) -- essentially, before the new object is created, find the max issue number of the issues associated with the issue's project, increment that, and use it for the new issue number...

like image 52
elijah Avatar answered Oct 19 '22 16:10

elijah