Ruby on rails 编辑现有记录会创建重复的Rails 5
我刚刚在创建发布在这里的新记录时遇到问题,所以不确定这是否相关 问题是,当我编辑现有记录时,可以很好地捕获更改,但它会创建一个副本,并使用看起来像散列的内容修改URL:。我使用友好的_ids gem动态地获取Ruby on rails 编辑现有记录会创建重复的Rails 5,ruby-on-rails,ruby,activerecord,rails-activerecord,Ruby On Rails,Ruby,Activerecord,Rails Activerecord,我刚刚在创建发布在这里的新记录时遇到问题,所以不确定这是否相关 问题是,当我编辑现有记录时,可以很好地捕获更改,但它会创建一个副本,并使用看起来像散列的内容修改URL:。我使用友好的_ids gem动态地获取:name字段,并将其用作唯一的url 我在数据库中有其他表,我可以编辑这些表 我看到了a,他的解决方案是将:id添加到许可参数中,我已经确保允许:slug和:id,但到目前为止还没有解决这个问题 我的控制器 形式
:name
字段,并将其用作唯一的url
我在数据库中有其他表,我可以编辑这些表
我看到了a,他的解决方案是将:id
添加到许可参数中,我已经确保允许:slug
和:id
,但到目前为止还没有解决这个问题
我的控制器
形式
解决方案
为清楚起见,我将添加以下设置:
通过“部分更新”使用相同的表单进行新建和更新:
发现我试图使用友好URL进行更新,导致id重复。使用以下解决方法:
def update
@coffeeshop = Coffeeshop.find(params[:id]) #<was Coffeeshop.friendly.find(params[:id])
if @coffeeshop.update(coffeeshop_params)
redirect_to @coffeeshop
else
render 'edit'
end
end
def更新
@coffeeshop=coffeeshop.find(params[:id])#尝试以下代码:
<% url = (params[:action]=="create" ? coffeeshops_path : coffeeshop_path(@coffeeshop.id.id)) %>
<% method = (params[:action]=="create" ? "post" : "put")%>
<%= form_for :coffeeshop, url: url, method: method do |f| %>|
...
<% end %>
更新
<%= form_for :coffeeshop, url: coffeeshop_path(@coffeeshop.id), method: :put do |f| %>
如果您对创建和更新使用相同的表单,\u,请使用以下代码:
<% url = (params[:action]=="create" ? coffeeshops_path : coffeeshop_path(@coffeeshop.id.id)) %>
<% method = (params[:action]=="create" ? "post" : "put")%>
<%= form_for :coffeeshop, url: url, method: method do |f| %>|
...
<% end %>
|
...
您使用的创建和更新表单与导致问题的表单相同。您需要添加method::put
进行更新。而且url
应该是coffeeshop\u路径(@coffeeshop)
您需要在新操作中初始化@coffeeshop
,然后可以使用相同的表单
def new
@coffeeshop = CoffeeShop.new
end
在你看来,
<%= form_for @coffeeshop do |f| %>
Rails可以根据传递的对象调用哪个操作
参考面向资源的风格您似乎对路线有问题。这就是为什么我要求您在前面的问题中显示您的路线粘贴表单和路线的代码文件路线和表单added@SimonCooper检查我的答案,它会起作用。现在检查选项。@coffeeshops
或@coffeeshop
?我的错,我会更新,它必须在编辑中相同,new
和form
如果它不起作用,那么我们可以添加另一个变量,如
,并将表单传递给,但我的朋友,您如何传递:id
以更新?只有@coffeeshop
(这里将是一个资源)而不是:coffeeshop
url应该像
是的,我实际上发现它正在更新,而没有将哈希添加到url中,但事实上它仍然在创建一个重复记录,因此显然没有编辑:id
'@coffeeshop.id.id'?
<%= form_for :coffeeshop, url: coffeeshops_path do |f| %>|
coffeeshops GET /coffeeshops(.:format) coffeeshops#index
POST /coffeeshops(.:format) coffeeshops#create
new_coffeeshop GET /coffeeshops/new(.:format) coffeeshops#new
edit_coffeeshop GET /coffeeshops/:id/edit(.:format) coffeeshops#edit
coffeeshop GET /coffeeshops/:id(.:format) coffeeshops#show
PATCH /coffeeshops/:id(.:format) coffeeshops#update
PUT /coffeeshops/:id(.:format) coffeeshops#update
<% url = (params[:action]=="create" ? coffeeshops_path : coffeeshop_path(@coffeeshop.id.id)) %>
<% method = (params[:action]=="create" ? "post" : "put")%>
<%= form_for :coffeeshop, url: url, method: method do |f| %>|
...
<% end %>
<%= form_for :coffeeshop, url: coffeeshop_path(@cofeeshop), method: put do |f| %>
def new
@coffeeshop = CoffeeShop.new
end
<%= form_for @coffeeshop do |f| %>