views:

30

answers:

2

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:

  1. get the User's document collection
  2. extract the titles to an array
  3. search the array for the new object's title
  4. if the title isn't found, save the object
  5. 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.

A: 

Rather than pulling their entire document list and iterating over them, a better way would be to do a find:

def controller_method_name
  ...
  title = params[:title]
  d = Document.find(:first, :conditions => ["title = :title", {:title => title.strip}]

  if !d.nil?
    #your safe, no document with this title exists
  else
    #pass the title to the Document model and generate a new name
  end
  ...
end

You could probably move most of that logic to the model, and have your controller be completely unaware that a new name needs or is being created.

Zachary
Doing a find will certainly help. However, this doesn't address the primary issue. Do you have any thoughts on that?
Craig
A: 

I decided that the easiest solution was simply to add 'copy YYYYMMDDHHMMSS' to the end of the file's name, where 'YYYYMMDDHHMMSS' is replaced by a date-time value.

Craig