【问题标题】:Rails 3.1 routing confusionRails 3.1 路由混乱
【发布时间】:2011-10-05 19:34:50
【问题描述】:

我正在尝试在我的应用程序中创建指向记录的链接:

<ul class="presentation-box">
  <% @presentations.each do |presentation| %>
   <li><%= link_to "Presentation", presentations_path(@presentation) %></li>
   <li><%= presentation.author %></li>
  <% end %>
</ul>

在路由文件中添加以下行:

resources :presentations
root :to => 'presentations#index'

由于某种原因,当我单击链接时,它会将我带到演示文稿索引视图。我认为它应该将我带到个人记录的展示视图?

我是否遗漏了一些明显的东西?

【问题讨论】:

    标签: ruby-on-rails routing ruby-on-rails-3.1 routes


    【解决方案1】:

    您的link_to 不正确。

    presentations_path 实际上会将您指向index,您希望presentation_path(presentation) 直接指向资源。

    另外,您可以只做&lt;%= link_to 'Presentation', presentation %&gt;,Rails 会为您构建正确的路径

    【讨论】:

    • 使用较短的版本是否可以将演示记录标题代替单词演示?
    • 是的,&lt;%= link_to @presentation.title, @presentation %&gt;。第一个参数是要显示的文本,第二个参数是资源,rails 会为你转换成路径。
    • Hmm..undefined method `title' for nil:NilClass
    • 糟糕,将 @presentation 更改为 presentation,这是您传递到 each 块中的参数。
    【解决方案2】:

    改成presentation_path(presentation)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多