无法访问评论对象中的用户

时间:2019-06-10 11:56:40

标签: ruby ruby-on-rails-4 ruby-on-rails-5

我有以下模型,发布,评论和用户。 Comment对象属于用户,并且用户有很多评论。但是,当尝试渲染视图以显示注释时,将无法访问该用户,并且会为nil:NilClass显示未定义的方法“ avatar”。附加的头像是与User类关联的方法。

这是评论控制器

class CommentsController < ApplicationController

    before_action :authenticate_user!, except: [:index, :show]
    before_action :set_commentable 

    def create
        @comment = @commentable.comments.new comment_params
        @comment.user = current_user
        @comment.save
        redirect_to @commentable, notice: "Comment Posted!"
    end

    def index
        @comments = @commentable.comments.all
        @comment = @commentable.comments.new comment_params
    end



    private

        def comment_params
            params.require(:comment).permit(:body)
        end

        def set_commentable
            @commentable = Post.find(params[:post_id])
        end

end

这是评论模型:

class Comment < ApplicationRecord
    belongs_to :user
    belongs_to :commentable, polymorphic: true
end

这是用户模型:

class User < ApplicationRecord

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  acts_as_voter

  has_many :posts
  has_many :comments
  has_one_attached :avatar


  validates :username, uniqueness: true
  validates :email, uniqueness: true

end

这是我要渲染的视图。我希望评论显示在帖子的显示视图的底部:

<p id="notice"><%= notice %></p>

<div class="w3-container w3-card w3-white w3-round m7" style="margin:auto; display:table; min-width: 500px; max-width: 800px;"><br>
        <% if @post.user.avatar.attached? %>
            <%= image_tag @post.user.avatar, class: "w3-circle avatar w3-left w3-margin-right", :style => "display: inline;" %>
        <% else %>
        <img src="https://www.w3schools.com/w3images/avatar2.png" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px">
        <% end %>
        <%= link_to @post do %>
        <span class="w3-right w3-opacity"><%= time_ago_in_words(@post.created_at) %> ago</span>
        <% end %>

        <h4><%= @post.user.name %></h4> <h5>@<%= @post.user.username%></h5>
        <hr class="w3-clear">
        <p><%= @post.content %></p>
        <% if user_signed_in? %>
        <hr class="w3-clear">
        <%= link_to like_post_path(@post), method: :put,  class: "w3-button w3-theme-d2 w3-margin-bottom" do%>
            <i class="fa fa-thumbs-up"></i>
            <span class="w3-badgeM"><%= @post.get_upvotes.size %></span>
        <% end %>    
        <button type="button" class="w3-button w3-theme-d2 w3-margin-bottom"><i class="fa fa-comment"></i></button>

        <% if current_user.id == @post.user_id %>
            <%= link_to edit_post_path(@post), class: "w3-button w3-theme-d1 w3-margin-bottom" do %>
                <i class="fas fa-pencil-alt"></i>
            <% end %>
            <%= link_to @post, method: :delete, data: {confirm: "Are you sure you want to delete this post?"}, class: "w3-button w3-theme-d1 w3-margin-bottom" do %>
                <i class="fas fa-trash-alt"></i>
            <% end %>
        <% end %>
        <% else %>
        <br >
        <% end %>

        <%= simple_form_for([@post, @post.comments.build]) do |f| %>
        <div class="field">
            <div class="control">
            <%= f.input :body, input_html: { class: 'textarea' }, wrapper: false, label_html: { class: 'label' }  %>
            </div>
        </div>
        <%= f.button :submit, 'Leave a reply', class: "button is-primary" %>
        <% end %>
        <% @post.comments.each do |comment|%>
        <div class="w3-container w3-card w3-round w3-margin" style="background-color: #f3f3f3; padding: 0px 5px 5px;" ><br>
            <% if comment.user.avatar.attached? %>
                <%= image_tag comment.user.avatar, class: "w3-circle avatar w3-left w3-margin-right", :style => "display: inline;" %>
            <% else %>
                <img src="https://www.w3schools.com/w3images/avatar2.png" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px">
            <% end %>
            <% if user_signed_in? %>

            <% end %>
            <span class="w3-right w3-opacity"><%= time_ago_in_words(comment.created_at) %> ago</span>
            <h6><%= comment.user.name %></h6> <p><strong>@<%= comment.user.username%></strong></p>
            <p style="max-height: 75px; overflow:auto;"><%= comment.body %></p>

        </div>
        <% end %>

    </div>

routes.rb文件:

Rails.application.routes.draw do
  devise_for :users
  #  :controllers => {registrations: 'registrations'}
  resources :posts do
    member do
      put "like" => "posts#upvote"
      put "unlike" => "posts#downvote"
    end
    resources :comments
  end   
  root "posts#index"
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

但是,当我尝试渲染它时,出现以下错误:

https://i.ibb.co/HV3qkr7/error.jpg

如果我查看数据库,则注释记录存在且具有正确的ID:

https://i.ibb.co/FXvPpSF/db.jpg

当我选择帖子后尝试在控制台中运行头像附加方法时,它似乎返回true且未引发任何错误:

https://i.ibb.co/X3k3mBq/console.jpg

有人可以帮助我,指出我出了什么问题吗? 谢谢:)

3 个答案:

答案 0 :(得分:0)

您的帖子似乎没有与之关联的用户。到目前为止您的错误消息已经缩小,很难看到,但是代码的第3行:

<% if @post.user.avatar.attached? %>

是发生错误的地方。发生这种情况不是因为用户没有头像,而是因为您正在尝试找到nilclass的头像。

您的两个选择是修复有问题的@post,使其与用户相关联(您可以在控制台上点其),或将行更改为:

<% if @post.user&.avatar.attached? %>

如果帖子的用户为nil,这将停止执行,并且仅返回false而不是爆炸。但是,如果应该在您的帖子中附加用户,那么我建议您解决此问题,而不要更改逻辑以解决没有用户的帖子。

答案 1 :(得分:0)

首先:没有像@post这样的实例变量,所以我将从此开始:)

第二:我建议将所有内容包装到实现Presenter设计模式的对象中。我将表示层与业务/持久层分开。

答案 2 :(得分:0)

这实际上是一个简单的修复!我只需要将评论视图包装在<% if !comment.user.nil? %>内,由于某种原因,第一个评论似乎没有与之关联的用户。

相关问题