【问题标题】:Rails button to duplicate object用于复制对象的 Rails 按钮
【发布时间】:2020-07-28 19:44:06
【问题描述】:

我需要放一个蓝色按钮来复制并保存具有相同信息的新对象,只需复制该行即可。

我尝试以下操作,但是当我单击蓝色按钮时,只需转到该行的显示 我不知道我错过了什么(也许很多)

gastos.html.erb

<button type="button" class="btn btn-sm btn-primary mr-2 command-delete">
       <%= link_to '', gasto, action: dup,  class: "fa fa-trash fa-fw text-light" %>
</button> 

gastos_controller.rb

def dup
    @gasto_dup = Gasto.find(params[:id]).dup
    render :new
end

点击蓝色按钮时的日志

Started GET "/gastos/152" for 127.0.0.1 at 2020-07-28 16:03:57 -0400
Processing by GastosController#show as HTML
  Parameters: {"id"=>"152"}
  User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Gasto Load (1.5ms)  SELECT "gastos".* FROM "gastos" WHERE "gastos"."id" = $1 LIMIT $2  [["id", 152], ["LIMIT", 1]]
  ↳ app/controllers/gastos_controller.rb:135:in `set_gasto'
  Rendering gastos/show.html.erb within layouts/application
  Rendered gastos/show.html.erb within layouts/application (Duration: 2.9ms | Allocations: 91)
[Webpacker] Everything's up-to-date. Nothing to do
Completed 200 OK in 133ms (Views: 102.7ms | ActiveRecord: 2.4ms | Allocations: 17541)

【问题讨论】:

  • 共享服务器的日志,我认为请求将发送到其他控制器

标签: ruby-on-rails ruby postgresql


【解决方案1】:

您只是在链接show 操作。

您不能将action: :dup 参数添加到link_to,这没有任何作用。第二个参数是 URL,action: :dup 只是作为 &lt;a&gt; 标签上的 action="dup" 属性转储到 DOM 中。

而不是这个...

link_to '', gasto, action: dup ...

你需要

link_to '', dup_gasto_path(gasto), ...

以上假设您的路线配置正确。

【讨论】:

  • 谢谢这是问题所在,在控制器中稍作修改@gasto = Gasto.find(params["format"].to_i).dup
  • @Poluxland 这是不正确的,你不应该那样使用params['format']。如果记录的 ID 是这样传入的,那么您的路由配置不正确。
【解决方案2】:

我在这里不是很熟悉,但可能值得尝试使用.clone 而不是.dup

https://www.rubyguides.com/2018/11/dup-vs-clone/

这两个方法都复制一个对象,不同的是dup不复制 对象属性。

【讨论】:

  • 我在使用 .clone 或 .dup 时遇到了同样的问题