RoR如何获取/ needs / 4的button_to路径而不是/needs.4?

时间:2013-12-24 12:56:24

标签: ruby-on-rails routing associations button-to

我仍然是RoR的新手,我正在尝试使用button_to删除按钮删除对象。 使用我编写的代码,当我尝试将其转换为/ needs /:id for destroy方法时,它会将我转到/needs.4而不是/ needs / 4。 通过需求控制器和需要new.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 "delete", '/needs/@userneed', method: :delete, data: { confirm: "You sure?"} %>

并在同一页面上:

@userneed = @current_user.needs.last

的routes.rb

delete "/needs/:id", to: "needs#destroy"
get "/needs/:id", to: "needs#show"

超级困惑,如果您知道如何解决它,请告诉我!

3 个答案:

答案 0 :(得分:1)

好的,这就是我修复它的方法:

<%= button_to "delete", {:controller => :needs, :action => "destroy", :id => current_user.needs.last.id}, :method => :delete, data: { confirm: "You sure?"} %>

所以我想这是两件事: 1)在正确的地方的花括号(我需要它们,因为仍有参数在花括号中的东西之后 2)以这种方式指定id而不是使用_path()方式

答案 1 :(得分:0)

尝试<%= 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>

答案 2 :(得分:0)

您需要运行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

在左侧获取路线名称,因此我需要使用其中一个路径路径助手来进行SchemasControllerdestroy操作...

schemas_path(@schema)

在运行时会自动替换(如果对象的ID为1)......

/schemas/1

所以在按钮中使用它......

<%= button_to "delete", schemas_path(@schema), method: :delete, data: { confirm: "You sure?"} %>

引用路由时应始终使用路由助手,因为它允许您通过调整routes.rb文件来更改所有路由助手。如果您需要阅读有关Rails路由的更多信息,可以在此处找到该指南...

http://guides.rubyonrails.org/routing.html