【问题标题】:Link_to with a triple nested route具有三重嵌套路由的 Link_to
【发布时间】:2014-04-26 04:54:54
【问题描述】:

我刚刚开始学习如何编程,作为实践,我正在尝试编写一个通用的类似 facebook 的程序。但是,当我输入下面提供的代码时,我不断收到以下错误:

没有路由匹配 {:action=>"new", :controller=>"cmets", :post_id=>nil, :user_id=>"4"} 缺少必需的键:[:post_id]

路线

  resources :users do
    resources :posts do
      resources :comments
    end
  end

查看

<% @user.posts.each do |p| %>     
<ul><b><%= p.id%></b></ul>
<ul><b><%= p.post%></b></ul>
<ul><em><%= p.created_at%></em></ul> 
<ul><%= link_to "Delete Post", [p.user, p], method: :delete %> </ul>
<ul><%= link_to "Comment", new_user_post_comment_path(@user, p.id) %> </ul>
<%end%>

控制器

def show
        @user = User.find(params[:user_id])
        @post = Post.find(params[:post_id)]
        @comment = Comment.find(params[:id])
        redirect_to user_path(@user)
    end

我在“p.id”的link_to部分尝试了许多不同的东西;我认为这可能给我带来了问题;但是,似乎没有任何效果。我已经尝试了许多其他关于如何处理与三重嵌套路由的链接的文章;但是,到目前为止没有任何效果。

我在这里做错了什么?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我猜,在所有用户的 cmets 中,有一条评论是post_id = nil。检查所有@user.comments 的post_id

    【讨论】:

      【解决方案2】:

      你的错误是这样的:

      没有路由匹配 {:action=>"new", :controller=>"cmets", :post_id=>nil, :user_id=>"4"} 缺少必需的键:[:post_id]

      该错误表示您没有发送嵌套路由所需的 post_id 参数。 nested 路由的全部意义在于您可以获得parent 资源的各种资源。这意味着如果不指定父资源,您将无法找到子资源

      要解决这个问题,我会推荐以下方法:

      <%= link_to "Delete Post", user_post_path(p.user, p), method: :delete %>
      <%= link_to "Comment", new_user_post_comment_path(@user, p) %>
      

      棘手的部分是我不知道您的哪个链接导致了错误


      您的控制器中还有一个错字:Post.find(params[:post_id])

      【讨论】:

        猜你喜欢
        • 2013-03-03
        • 2017-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-18
        • 2011-07-09
        • 2016-11-05
        相关资源
        最近更新 更多