How to maintain duplicate record in database?
My table contains two columns Title and Description. I want to provide a functionality to user to create duplicate page for existing page.
Like for existing page database store value like.
Title1 , Description1
When user clicks on duplicate page button I want to create a duplicate entry for the existing page like this.
1) Click First Time
Copy_1_Title1, Descriptio开发者_运维百科n1
2) Click Second Time
Copy_2_Title1, Description1
How can I create this type of functionality ? How should be my database for this ? Is this a proper way ?
I think you should create third column and name it for example copy_number, and then before creating record you can find it by title and if title exist you can get value of copy_number and increment it. Then you can use this number to display titles as you wish:
"copy_#{record.copy_number}_#{record.title}" or something like this.
@bor1s has suggested very right solution.
But for the interest you can use this mthod for duplication :)
class Page < AR::Base
def duplicate
# new_page = self.clone
new_page = Page.new self.attributes.except(:id, :created_at, :updated_at)
copy = (self.title.match(/Copy_(\d)+.*/).try([1]) || 0) + 1
new_page.title = "Copy_#{copy}_#{self.title}"
new_page.save
end
end
精彩评论