неопределенный метод `name 'для nil: NilClass, пока объект существует - PullRequest
0 голосов
/ 23 ноября 2018

Я создаю блог, используя ruby ​​на рельсах, и пока я кодирую комментарии, у меня появляется странная ошибка, из-за которой я не могу найти решение для

Я пытаюсь прочитать имя пользователяиз comment.user и возвращает этот erorr

undefined method `name' for nil:NilClass

Если я проверил объект пользователя, я вижу данные внутри

<%= comment.user.inspect %>

Я правильно добавил связи между моделями

Модель пользователя

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


  has_many :comments, dependent: :destroy


end

Почтовая модель

class Post < ApplicationRecord
    belongs_to :user
    has_many :comments, dependent: :destroy
end

Комментарий модели

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

Комментарий Вид

<strong><%= comment.user.name %>:</strong><%= comment.body %><br><br>

Любая помощьпожалуйста?

Редактировать 2:

Комментарии код контроллера

class CommentsController < ApplicationController
  before_action :set_comment, only: [:show, :edit, :update, :destroy]

  # GET /comments
  # GET /comments.json
  def index
    @comments = Comment.all
  end

  # GET /comments/1
  # GET /comments/1.json
  def show
  end

  # GET /comments/new
  def new
    @post = Post.find params[:post_id]
  end

  # GET /comments/1/edit
  def edit
  end

  # POST /comments
  # POST /comments.json
  def create
    @comment = Comment.new(comment_params)
    @post = Post.find params[:post_id]
    @comment.user_id = current_user.id 
    respond_to do |format|
      if @comment.save
        format.html { redirect_to @post, notice: 'Comment was successfully created.' }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { render :new }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /comments/1
  # PATCH/PUT /comments/1.json
  def update
    respond_to do |format|
      if @comment.update(comment_params)
        format.html { redirect_to @comment, notice: 'Comment was successfully updated.' }
        format.json { render :show, status: :ok, location: @comment }
      else
        format.html { render :edit }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /comments/1
  # DELETE /comments/1.json
  def destroy
    @comment.destroy
    respond_to do |format|
      format.html { redirect_to comments_url, notice: 'Comment was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_comment
      @comment = Comment.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def comment_params
      params.require(:comment).permit(:body, :user_id, :post_id)
    end
end

Ответы [ 3 ]

0 голосов
/ 23 ноября 2018

попробуйте это <%= comment.user.try(:name) %>.

Возможно, некоторые комментарии не содержат значения пользователя.

0 голосов
/ 23 ноября 2018

try метод определен для класса Object и класса NilClass в Rails и не является частью самого Ruby.Вы можете использовать try, когда имеете дело с потенциальными объектами nil.

<%= comment.user.try(:name) %>.

Когда вы используете try в вашем случае, исключение NoMethodError не будет возбуждено, и nil будетвместо принимающего объекта возвращается объект nil или NilClass.

Для получения дополнительной информации вы можете посмотреть эту ссылку

0 голосов
/ 23 ноября 2018

Можешь попробовать?

<%= comment.user.name if comment.user %>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...