myowin76
7/19/2013 - 3:55 PM

rails3 copy the record and create new

rails3 copy the record and create new

// album.rb Model
class Album < ActiveRecord::Base
  def copy
    self.class.new.tap do |new_album| 
      attributes.each do |key, value|
        new_album.send("#{key}=", value) unless key == "id" 
      end
      new_album.save
    end 
  end
end

// albums_controller.rb
def copy
  original_album = Album.find(params[:id])
  @album = original_album.copy 
  redirect_to edit_album_path(@album),
    :notice => "This is a copy of #{original_album.title}"
end


// albums/show.html.erb
<%= button_to 'Copy', copy_album_path(@album) %> # http post by default
<% link_to "Copy", copy_album_path(@album), :method => :post %>  #http get by default

// routes.rb
resources :albums do
  member do 
    post :copy
  end 
end