【问题标题】:Routing GET request to 'index' action with optional :sort parameter使用可选的 :sort 参数将 GET 请求路由到“索引”操作
【发布时间】:2013-01-27 21:40:57
【问题描述】:

作为 Edx 的 SaaS 课程的一部分,我正在努力使用我的第一个 rails 应用程序。卡住了一个大概相当基本的路由问题。

搜索、反复试验只是让我在下面进行了适度的尝试,所以我现在第一次尝试使用 stackoverflow。

任务是使“电影”表的“标题”列在单击标题时可排序。到目前为止,我已经添加了下面标记为粗体的 'link_to' .. 'movie_path...' 部分。

%h1 All Movies
%table#movies
  %thead
    %tr
      %th= link_to "Movie Title", movie_path(:sort => "title")
      %th Rating
      %th Release Date
      %th More Info
  %tbody
  ...

我的 routes.rb 文件只有基于 resources :movies 的自动生成的路由。 为了处理“排序”选项,我将 MoviesController 的基本“索引”方法更改如下:

def index
  sort = params[:sort]
  @movies = Movie.find(:all, **:order => "title"**) **if :sort == "title"**
end

现在我收到此错误消息:

Started GET "/movies" for 127.0.0.1 at 2013-01-27 14:58:55 -0600
  Processing by MoviesController#index as HTML
Rendered movies/index.html.haml within layouts/application (1.6ms)
Completed 500 Internal Server Error in 20ms

ActionView::Template::Error (No route matches {:action=>"show", :controller=>"movies"}):
    4: %table#movies
    5:   %thead
    6:     %tr
    7:       %th#title_header= link_to "Movie Title", movie_path
    8:       %th Rating
    9:       %th Release Date
    10:       %th More Info
  app/views/movies/index.html.haml:7:in `_app_views_movies_index_html_haml__237103960__639242128'

问题:

  • 我应该定义一个单独的方法“排序”而不是在index 中包含“排序”选项吗?
  • 无论哪种情况,如何正确路由请求?

提前致谢!

【问题讨论】:

  • 在您的视图中将movie_path 替换为movies_path
  • 魔鬼和细节......谢谢!

标签: ruby-on-rails routes


【解决方案1】:

那是一堂很棒的课!当他们说要问你是否自己想不通时,我看到你在注意。

正如评论所建议的,您需要movies_path,但您的代码还有另一个问题。

您当前设置了一个 sort 变量,但随后您正在检查 :sort,它不是变量而是符号 - 基本上是一个常量。

此外,当您将if 放在行尾时,它会影响整行。所以你现在拥有它,你永远不会分配@movies

希望对你有帮助。

【讨论】:

  • 谢谢,杰夫。确实很棒的课。在修正了你的观点和其他一些观点之后,它同时工作了..
猜你喜欢
  • 1970-01-01
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 2019-12-07
相关资源
最近更新 更多