【问题标题】:How to use Link_to with nested resources如何将 Link_to 与嵌套资源一起使用
【发布时间】:2013-04-29 11:31:03
【问题描述】:

我是 Rails 的新手。

我创建了一个 Web 应用程序,我可以通过 /posts/123/comments//posts/123/comments/new 访问,但我不知道如何在索引视图中使用 link_to 来显示具体评论,当我尝试链接它时,出现“没有路线”或“未定义的符号”。

我在模型和routes.rbpost_comments GET /posts/:post_id/sensors(.:format) 中定义的帖子和cmets 之间存在嵌套的have_many 关系,当我执行rake 路由时会出现comments#index

我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 nested-resources


    【解决方案1】:

    如果您定义了嵌套资源(当然您的模型 CommentPost 是关联的)

    resources :posts do
     resources :comments
    end
    

    您可以将评论链接如下

    <!-- /posts/:post_id/comments/:id -->
    <%= link_to 'Show', [@comment.post, @comment] %>
    

    我写了full example of nested resources in a past blog post

    【讨论】:

    • 我已将代码更改为 并且它没有运行...出现未定义的方法发布。我该怎么做?谢谢!
    • 这可能是因为您的Comment 模型与Post 没有关联。你的Comment 模型中应该有belongs_to :post。如果没有,这是正常的,它是未定义的。您还可以将 @comment.post 替换为包含评论的 Post 对象(在您的情况下可能是 item)。
    • 这对我不起作用:它抱怨 post_comment_path 未定义(rake routes 中显示的路由是 post_comments,复数)
    【解决方案2】:

    在尝试了所有答案后,它并没有完全奏效,但我找到了解决它的方法。 在第一时间,我使用了

    post_cmets_url(@post,comment)

    comment 是 @post.each 中的项目。

    它使用 .相反/就像“post/34/cmets.2”一样,我用单数形式修复了它:

    post_comment_url(@post,comment)

    感谢您的帮助!

    【讨论】:

      【解决方案3】:

      从第一列获取方法名

         rake routes
      

      并相应地传递 ID。当然,方法名称的后缀是_path ir _url 要了解更多信息,请访问Rails guide

      【讨论】:

        【解决方案4】:

        除了 toch 的回答,您还可以在 Rails 控制台的帮助下调试您的 link_to 调用。

        为此,您需要在控制台中加载视图助手:

        irb(main):001:0> include ActionView::Helpers::UrlHelper
        => Object
        irb(main):002:0> helper.link_to "posts", app.posts_path
        => "<a href=\"/posts\">foo</a>"
        

        另一个类似Rake routes的工具,用于路由调试是:https://github.com/schneems/sextant

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-23
          • 2017-01-24
          • 1970-01-01
          • 1970-01-01
          • 2023-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多