【问题标题】:Rails: Redirect to user's profile inside commentsRails:重定向到评论中的用户个人资料
【发布时间】:2023-03-12 01:02:01
【问题描述】:

我的 Rails 应用中有一个非常简单的评论系统 - 我想允许用户点击评论者的姓名来访问他的个人资料。

但没有任何成功 - 我不确定我错过了什么。

<% @comments.each do |comment| %>

          <p><a href="<%= user_path(@comment.user_id) %>" style="text-decoration : none"><%= image_tag comment.user.image, class: "img-circle", width: "30x30" if comment.user %><font class="small" color="#28c3ab"> @<%= comment.user.name if comment.user %></font></a> 

<% end %>

但是我没有路由匹配错误:

No route matches {:action=>"show", :controller=>"users", :id=>nil} missing required keys: [:id]

任何想法我错过了什么?我知道这很容易,但我现在没有想法。我应该在我的控制器中的哪里添加这个调用?

【问题讨论】:

    标签: ruby-on-rails comments associations acts-as-commentable


    【解决方案1】:

    我发现你的问题可能是@comment

    改变:

    user_path(@comment.user_id)
    

    到:

    user_path(comment.user_id)
    

    【讨论】:

    • 这是一样的。在内部,第一个调用被转换为第二个。
    • @zacchj 检查这可能是问题
    • 我怎么会错过 :( !谢谢老兄
    【解决方案2】:

    检查@comment.user_id 的值。可能没有为实例分配user_id,值为nil

    【讨论】:

    • 奇怪,cmets 与用户相关联 => 2.1.1 :006 > Comment = Comment.first 评论加载(0.2ms)选择“cmets”。*从“cmets”按“cmets”排序。 “id” ASC LIMIT 1 (irb):6: 警告: 已初始化常量评论 /Users/jeremyzaccherini/Desktop/fundmymac/app/models/comment.rb:1: 警告:评论的先前定义在这里 => #
    • 如您所见,每个 cmets 都有一个 user_id 关联
    • 您的代码只是演示了第一个 Comment 有一个 user_id。你确定每条评论记录都有一个用户ID吗?运行Comment.pluck(:user_id) 并检查返回的数组是否包含nil 值。
    • 这是它返回的内容:2.1.1 :001 > Comment.pluck(:user_id) (0.2ms) SELECT "cmets"."user_id" FROM "cmets" => [3, 13]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多