尝试将现有属性克隆到我的数据库中的新条目时,会出现奇怪的保存错误

时间:2012-03-12 00:29:17

标签: ruby-on-rails save clone

controller(tce_p​​arams_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

模型(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

视图

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

路线

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

当我运行此操作时,我收到错误消息“

Tce param setsController#clone中的NoMethodError

未定义的方法`save'for#(表不存在)

/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:in require' 脚本/服务器:3

请求

参数:

{ “ID”=> “中3”}

显示会话转储


响应

接头:

{ “内容类型”=> “中”,  “缓存控制”=> “中无缓存”}

使用此代码我得到了

处理TceParamSetsController#clone(适用于2012-03-12 09:36:37的127.0.0.1)[GET]   参数:{“id”=>“2”}   TceParamSet加载(1.5ms)SELECT * FROM“tce_p​​aram_sets”WHERE(“tce_p​​aram_sets”。“id”= 2) 警告:无法批量分配这些受保护的属性:id   SQL(0.3ms)BEGIN   TceParamSet加载(0.8ms)SELECT“tce_p​​aram_sets”.id FROM“tce_p​​aram_sets”WHERE(“tce_p​​aram_sets”。“name”='Perf:14520 - Fairshare TM 4.00(最新) - PTS 6.00(最新的TM-4.00分支) - NA Wireline ')限制1   SQL(0.4ms)ROLLBACK

为什么会这样?我没有给id任何值,但它说我正在尝试分配ID ...

1 个答案:

答案 0 :(得分:0)

看起来克隆方法的返回值不是ActiveRecord对象,因此您返回的值上不存在save方法。此外,模型中的克隆方法似乎具有循环引用,因为它在其正文中调用您的方法“clone”。所以我不确定这究竟是怎么回事。

首先,确保您的返回值确实是ActiveRecord对象,并考虑使用“super”来调用ruby对象的clone方法。