简体   繁体   中英

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.

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...

您可以在Project问题关联上使用counter_cache并覆盖Project的decrement_counter以不执行任何操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM