【发布时间】:2012-03-19 18:09:59
【问题描述】:
刚开始使用 Rails,但在定义路线时遇到问题。我似乎没有任何文档可以解决这个问题,而且我得到一个未定义的局部变量或方法错误。
我需要单击一个链接并执行特定操作,sortit。 sortit 没有视图,因为它对 mystuff 对象进行排序,然后重定向到索引页面。当我使用其中一种预定义操作时,实际上一切正常。当然,预定义的操作都不是我想要做的。
我的 /config/routes.rb 文件:
match "/mystuff/sortit'", :controller => "mystuff", :action => "sortit"
resources :mystuff
我的 /app/controllers/mystuff_controller.rb 文件
class MystuffController < ApplicationController
....
def sortit
@mystuff.sort
redirect_to_mystuff_path
end
....
end
我的 /app/views/mystuff/index.html.haml 文件:
-# This file is app/views/mystuff/index.html.haml
%h1 All My Stuff
%table#mystuff
%thead
%tr
%th= link_to raw("Type"), sortit
....
正如我所说,当我用预定义的操作替换 sortit 时,就会执行该操作。但是 sortit 失败并出现此错误:
undefined local variable or method `sortit' for #<#<Class:0x9997a10>:0x997c0f8>
app/views/mystuff/index.html.haml:7:in `_app_views_mystuff_index_html_haml__61272557_87671610'
那么我错过了什么以及如何在单击生成的 Type 链接时执行 sortit?
谢谢!
PS:我的 rake 路由输出:
mystuff GET /mystuff (.:format) {:action=>"index", :controller=>"mystuff"}
....
mystuff_sortit /mystuff/sortit (.:format) {:controller=>"mystuff", :action=>"sortit"}
....
所以 rake routes 显示我的路由名称为 mystuff_sorit - 但不是在对象名称前添加操作吗?不应该是 sortit_mystuff 吗?
【问题讨论】:
-
当然上面的mystuff其实是mystuffs ....
-
我想你想为 :as => 'sortit' 的路由匹配行添加一个键,然后调用 sortit_path 或 sortit_url 而不仅仅是 sortit。
-
@Thanatos - 谢谢 - 虽然当我点击 sortit 链接时它仍然失败,但在显示 index.html 页面时并没有产生错误。在 routes.rb 中,我添加了 :as 在路由中 - 并在 index.html.haml 中添加了 sortit_url。但是,这是在哪里记录的? :action=>"sortit" 被指定。为什么 :as 完全需要? _url“后缀”记录在哪里?
routes.rb:
匹配 "/mystuff/sortit'", :controller => "mystuff", :action => "sortit", :as=>"sortit"
%th= link_to raw("Type"), sortit_url
-
@Thantos - 该更改导致 rake 路由输出发生此更改: sortit /mystuff/sortit (.:format) {:controller=>"mystuff", :action=>"sortit"} - 那么代码生成的详细记录在哪里呢?
-
这确实会为 Type: Type 生成一个 url - 但现在抛出一个 ActiveRecord::RecordNotFound 错误并显示显然正在尝试执行操作:ActiveRecord::RecordNotFound in MystuffController#show 找不到 Mystuff with id=sortit app/controllers/mystuff_controller.rb:5:in `show'
标签: ruby-on-rails ruby methods routes undefined