【问题标题】:Link to resource链接到资源
【发布时间】:2011-04-13 08:10:39
【问题描述】:

我已经创建了模型、视图和控制器:

$ rails generate scaffold Post name:string title:string content:text

我运行服务器,如果我在浏览器中打开 http:\localhost:3000\posts,我会看到帖子列表。 现在我需要创建指向此页面的链接。比如:

<%= link_to("settings", { :controller => 'groups', :action => 'index'}) %>

但打开此页面时出现错误:

Couldn't find Group with ID=index

如何创建指向 http:\localhost:3000\posts 的链接,在这种情况下我应该使用哪个操作?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我认为路径助手在这些情况下非常出色。你可以这样做:

    <%= link_to("Posts", posts_path) %>
    

    在这种情况下,posts_path 将链接到 http://localhost:3000/posts

    当您在 routes.rb 中使用 use resources :posts 时,您会自动获得一些路径助手。例如:

    posts_path            # /posts
    post_path(@post)      # /posts/1
    edit_post_path(@post) # /posts/1/edit
    new_post_path         # /posts/new
    

    【讨论】:

      【解决方案2】:

      如果你有这样的路线:

      resources :groups
      

      config/routes.rb 中,您将拥有助手groups_path。您可以使用rake routes 查看您的所有路线和助手,但在这种情况下,您将拥有:

      groups_path
      group_path(@group)
      edit_group_path(@group)
      

      Polymorphic Routes Documentation

      【讨论】:

        猜你喜欢
        • 2014-11-05
        • 2010-09-06
        • 2021-12-01
        • 1970-01-01
        • 2010-10-03
        • 2011-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多