I have a User model which has_many Documents. Each Document's title must be unique within the scope of a User. This works as expected.
class Document < ActiveRecord::Base
has_many :documents, :dependent => :delete_all
end
class Document < ActiveRecord::Base
belongs_to :user
validates_presence_of :title
validates_uniqueness_of :title, :scope => :user_id
end
When I clone a Document, I want to ensure that its title is unique. OSX will append 'copy' to an document that is copied in Finder. If the object's name ends with 'copy', it will add an incremented numerical value, starting with 2 (e.g. 'foo copy 2'). I would like to reproduce this behavior.
It seems like I would need to do the following in the ResumeController's copy action:
- get the User's document collection
- extract the titles to an array
- search the array for the new object's title
- if the title isn't found, save the object
- if the title is found (could be mulitple, like 'foo Copy', 'foo Copy 2'), append 'Copy' to the end of the title or increment the number. The regex pattern 'Copy[ 0-9]*$' seems to locate a correct match.
At the moment, the copy logic is in the ResumeController, but it seems more appropriate to add it to the Document model.
Any advice is appreciated.