Search code examples
ruby-on-railssaveclone

Getting weird save error when trying to clone existing attributes to new entry in my db


controller (tce_params_controller)

def clone
  tce_params = TceParamSet.find(params[:id])
  puts "This is tce_params"
  puts tce_params
  cloned_tce_params = tce_params.clone
  puts "This is cloned_tce_params"
  puts cloned_tce_params
  if @saved == true
    flash[:notice] = 'Item was successfully cloned.'
    redirect_to edit_tce_param_set_path(@cloned_tce_params)
  else
    flash[:notice] = 'ERROR: Item can\'t be clone'
    puts cloned_tce_params.errors
    redirect_to system_data_path
  end
end

Model(TceParamSet)

def clone
  cloned_tce_params = TceParamSet.new(self.attributes)
puts "this is attributes in model"
puts cloned_tce_params.attributes
cloned_tce_params.id = nil
if cloned_tce_params.save
  cloned_tce_params = cloned_tce_params.name + "(cloned)"
  @saved = true
else
  @saved = false
end
return cloned_tce_params
end

views

=link_to "Clone", clone_test_group_path(test_group), :method => :clone, :class => :tce_param_sets

Route

map.connect '/tce_param_sets/:id/clone', :controller => "tce_param_sets", :action => "clone"

When I run this, I get an error saying"

NoMethodError in Tce param setsController#clone

undefined method `save' for #(Table doesn't exist)

/usr/local/rvm/gems/ruby-1.8.7-p357@rails238/gems/rails-2.3.8/lib/commands/server.rb:111 /usr/local/rvm/rubies/ruby-1.8.7-p357/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in gem_original_require' /usr/local/rvm/rubies/ruby-1.8.7-p357/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:inrequire' script/server:3

Request

Parameters:

{"id"=>"3"}

Show session dump


Response

Headers:

{"Content-Type"=>"", "Cache-Control"=>"no-cache"}

using this code I get

Processing TceParamSetsController#clone (for 127.0.0.1 at 2012-03-12 09:36:37) [GET] Parameters: {"id"=>"2"} TceParamSet Load (1.5ms) SELECT * FROM "tce_param_sets" WHERE ("tce_param_sets"."id" = 2) WARNING: Can't mass-assign these protected attributes: id SQL (0.3ms) BEGIN TceParamSet Load (0.8ms) SELECT "tce_param_sets".id FROM "tce_param_sets" WHERE ("tce_param_sets"."name" = 'Perf: 14520 - Fairshare TM 4.00 (latest) - PTS 6.00 (latest TM-4.00 branch) - NA Wireline') LIMIT 1 SQL (0.4ms) ROLLBACK

Why is this happening? I am not giving id any value yet it is saying I am trying to assign ids...


Solution

  • It would appear that the return value from your clone method is not an ActiveRecord object so the save method doesn't exist on the value you're returning. Also, the clone method in your model appears to have a circular reference as it's calling your method "clone" in it's body. So I'm not sure how exactly this could be working at all.

    First, ensure your return value is indeed an ActiveRecord object and consider using "super" to call the ruby object's clone method.