我需要复制一条记录,除了cource的ID之外,还有原始的相同属性.我做:
在视图中:
<%= link_to "Duplicate", :action => "clone", :id => Some_Existing_ID %>
Run Code Online (Sandbox Code Playgroud)
在控制器中:
def clone
@item = Item.find(params[:id]).clone
if @item.save
flash[:notice] = 'Item was successfully cloned.'
else
flash[:notice] = 'ERROR: Item can\'t be cloned.'
end
redirect_to(items_path)
end
Run Code Online (Sandbox Code Playgroud)
但没有任何反应!在控制台中我发现克隆生成没有ID的副本.
有任何想法吗 ?
*> BTW:我正在运行Rails 2.3.5和Ruby 1.8
避免使用克隆方法。它不再受支持。clone 方法现在委托使用 Kernel#clone 来复制对象的 id。
# rails < 3.1
new_record = old_record.clone
# rails >= 3.1
new_record = old_record.dup
Run Code Online (Sandbox Code Playgroud)
确保默认的克隆行为适合您。根据您的验证规则,克隆的记录实际上可能无效。
尝试使用@item.save!
not@item.save
并检查是否引发异常。您还可以直接在控制台实例中尝试该代码。
In Console I figured out that clone generates the copy without ID.
Run Code Online (Sandbox Code Playgroud)
这是真的。#clone
实际上创建了一个克隆但不保存记录。这就是为什么您需要在操作中调用保存方法,这就是您实际执行的操作
if @item.save # <-- here you save the record
flash[:notice] = 'Item was successfully cloned.'
else
flash[:notice] = 'ERROR: Item can\'t be cloned.'
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6679 次 |
最近记录: |