我对 RoR 还很陌生,我正在尝试使用button_to删除按钮删除对象。不过,使用我编写的代码,当我尝试将其转换为/needs/:id 以进行销毁方法时,它会让我进入/needs.4 而不是/needs/4。"需求"是通过需求控制器和 neednew.html.erb 页面创建的,然后显示在用户的显示页面中。从那里,用户应该能够删除他/她的需要。这是我得到的错误:
ActiveRecord::RecordNotFound in NeedsController#destroy
Couldn't find Need with id=@userneed
Rails.root: /Users/mcn/Dropbox/Code/GA/Projects/GA_projects/p4_final/flatcircle
Application Trace | Framework Trace | Full Trace
app/controllers/needs_controller.rb:20:in `destroy'
Request
Parameters:
{"_method"=>"delete",
"authenticity_token"=>"Fv6EcMNJQEjtw1naQVMw77lkCGjTJR7ui2FD53aoZfc=",
"id"=>"@userneed"}
这是我的代码:
Needs_controller:
def destroy
Need.find(params[:id]).destroy
redirect_to :controller => :users, :action => :show, :id => current_user.id, :flash => { :success => "Your search post was deleted." }
end
用户的显示页面button_to行:
<%= button_to "delete", '/needs/@userneed', method: :delete, data: { confirm: "You sure?"} %>
并在同一页面上:
@userneed = @current_user.needs.last
路线.rb
delete "/needs/:id", to: "needs#destroy"
get "/needs/:id", to: "needs#show"
超级困惑,如果你知道如何解决它,请告诉我!
好的,这就是我修复它的方式:
<%= button_to "delete", {:controller => :needs, :action => "destroy", :id => current_user.needs.last.id}, :method => :delete, data: { confirm: "You sure?"} %>
所以我想这是两件事:1)花括号在正确的位置(我需要它们,因为在大括号中的东西之后仍有争论2) 以这种方式指定 id,而不是使用 _path() 方式
尝试<%= button_to "delete", '/needs/<%= @userneed %>', method: :delete, data: { confirm: "You sure?"} %>
和@userneed = @current_user.needs.last.id
但我认为最好使用链接而不是按钮......类似<a href="<%=model_path(@model) %>" data-method="delete" data-confirm="are you sure?">delete</a>
运行rake routes
然后查看所需的路径。例。。。
schemas GET /schemas(.:format) schemas#index
POST /schemas(.:format) schemas#create
new_schema GET /schemas/new(.:format) schemas#new
edit_schema GET /schemas/:id/edit(.:format) schemas#edit
schema GET /schemas/:id(.:format) schemas#show
PUT /schemas/:id(.:format) schemas#update
DELETE /schemas/:id(.:format) schemas#destroy
取左边的路由名称,这样我才能到达SchemasController
,这是我需要使用路由路径助手之一destroy
操作......
schemas_path(@schema)
这将在运行时自动替换为(如果对象的 ID 为 1)...
/schemas/1
所以要在按钮中使用它...
<%= button_to "delete", schemas_path(@schema), method: :delete, data: { confirm: "You sure?"} %>
引用路由时,应始终使用路由帮助程序,因为它允许您通过调整routes.rb
文件来更改所有路由帮助程序。如果您需要阅读有关Rails Routing的更多信息,可以在此处找到该指南...
http://guides.rubyonrails.org/routing.html