【问题标题】:Simple routing in RailsRails 中的简单路由
【发布时间】:2013-01-05 06:48:31
【问题描述】:

我正在尝试从用户显示视图中销毁链接。

所以来自/users/1

我想在teacher_student_links 控制器中访问destroy 操作。

第一次尝试:

<%= link_to 'destroy', :controller => "teacher_student_links", :action => "destroy", :id => @user.id %>

这会失败,因为它会路由到指定控制器中的“显示”操作。 所以第一个问题:为什么它指向“show”动作而不是“destroy”?我试图用括号将上面的内容括起来,也得到了一个无意义的错误。

第二次尝试:

config/routes.rb

match '/bye_teacher' => 'teacher_student_links#destroy'

查看

<%= link_to 'destroy', '/bye_teacher', :user_id => @user.id %>

也试过了,

<%= link_to 'destroy', '/bye_teacher', :user_id => @user %>

这两行都正确指向了指定的控制器和动作,但是参数没有传入。(没有ID错误找不到用户)

第二个问题:在这种情况下我是否以错误的方式传递变量?

问这两个问题有点尴尬,但我想知道这些问题背后的原因。

更新:

<%= link_to 'destroy', teacher_student_links_path(:user_id => @user), :method => :delete %>

给予

没有路线匹配 [DELETE] "/teacher_student_links"

<%= link_to 'destroy', teacher_student_links_path(@user), :method => :delete %>

给予

No route matches [DELETE] "/teacher_student_links.1"

...所以我跑了

rake routes 我得到了

DELETE /teacher_student_links/:id(.:format) teacher_student_links#destroy

【问题讨论】:

标签: ruby-on-rails routing link-to


【解决方案1】:

你给错了路径

<%= link_to 'destroy', teacher_student_links_path(@user), :method => :delete %>

应该是这样的:

<%= link_to 'destroy', teacher_student_link_path(@user), :method => :delete %>

当你运行“rake routes”时,第一列会告诉你路径

【讨论】:

    【解决方案2】:
    match "/bye_teacher/:id" => "teacher_student_links#destroy"
    
    
    <%= link_to 'destroy', teacher_student_links_path(:id), 
    :confirm => 'Are you sure you want to destroy this teacher?', :method => :delete %>
    

    这也应该在视图中起作用:

    <%= link_to 'Destroy', :action => 'destroy', :id => @user.id, :method => :delete %>
    

    Rails Routing from the Outside In

    【讨论】:

    • 在这种情况下,你不需要在路由中放置匹配线,对吧?
    • 可能。您可以从命令行运行 rake routes 以确保 RESTful 路径存在。
    • 你的答案实际上是我第一次尝试的。不过我遇到了这个错误:No route matches [DELETE] "/teacher_student_links.1" 即使 rake 路由给了DELETE /teacher_student_links/:id(.:format) teacher_student_links#destroy 我很困惑为什么路径指向..links.1 而不是..links/1
    • @MaximusS 是的,您的teacher_student_links_path 未在路线中设置。我的第二种方法有效吗?
    • 没有。这与我在问题中描述的第一次尝试相同。 :(
    猜你喜欢
    • 1970-01-01
    • 2011-05-23
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多