简体   繁体   English

Ruby on Rails:无法通过评论访问用户属性

[英]Ruby on Rails: Can't access User Attributes From a Comment

In this application, I have a Recipe model, User model(Devise), and a Comment model. 在此应用程序中,我有一个配方模型,一个用户模型(Devise)和一个注释模型。

class User < ActiveRecord::Base
  has_many :recipes
  has_many :comments
end

class Recipe < ActiveRecord::Base
  belongs_to :user
  has_many :comments, :dependent => :destroy
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :recipe
end

This is what my Comments Controller looks like. 这就是我的注释控制器的外观。

class CommentsController < ApplicationController

  def create
    @recipe = Recipe.find(params[:recipe_id])
    @comment = @recipe.comments.build(comment_params)
    @comment.user = current_user
    if @comment.save
      redirect_to root_path #change this the the appropriate path later
    end
  end

  private
  def comment_params
    params.require(:comment).permit(:content)
  end
end

This is the error that I am getting 这是我得到的错误

ActionView::Template::Error (undefined method `first_name' for nil:NilClass):
68:     <p><%= @recipe.comments.count %> Comments</p>
69:     <% @recipe.comments.each do |comment| %>
70:       <p><%= comment.content %><p>
71:       <%= comment.user.first_name %>
72:     <% end %>
73:   </div>
74: </div>

So the problem occurs when I try accessing the first_name attribute. 因此,当我尝试访问first_name属性时,就会出现问题。 If I do just 'comment.user' it spits out # User:0x007f8f4f9b6780. 如果我只是执行'comment.user',它会弹出#User:0x007f8f4f9b6780。

I looked in the Rails Console and saw that my comments are saving. 我在Rails控制台中查看,发现我的评论正在保存。 In the Rails Console, I am able to do 在Rails Console中,我可以

@recipe = Recipe.first
@recipe.comments.first.user.first_name => "John"

This is the actual code that's failing 这是实际的代码失败

<% @recipe.comments.each do |comment| %>
  <% byebug %>
  <p><%= comment.content %><p>
  <p><%= comment.user.first_name %></p>
<% end %>

I tried using byebug to debug, and I'm able to do 'comment.user.first_name' => John 我尝试使用byebug进行调试,并且能够执行'comment.user.first_name'=> John

I'm not sure what I have wrong here and would appreciate the help. 我不确定在这里有什么问题,将不胜感激。 Rails 4.2.0 btw Rails 4.2.0 btw

Edit: RecipeController#Show 编辑:RecipeController#显示

class RecipesController < ApplicationController
  before_action :find_user, only: [:edit, :update, :show, :destroy]
  before_action :find_recipe, only: [:edit, :update, :show, :destroy]


  ...

  def show

  end

  private

  def find_user
    @user = User.find(params[:user_id])
  end

  def find_recipe
    @recipe = Recipe.find(params[:id])
  end
end

Comment Form Partial 评论表格部分

<div class="container">
  <% if user_signed_in? %>
  <%= form_for([@recipe.user, @recipe, @recipe.comments.build]) do |f| %>
    <%= f.label :content %><br>
    <%= f.text_area :content %><br>
    <br>
    <%= f.submit class: "btn btn-default" %>
  <% end %>
<% end %>
</div>

Because you're iterating over the collection of Comments 因为您要遍历评论的集合

@recipe.comments.each

The error you've mentioned occurs, because ONE of comments doesn't have user set (which causes first_name call on nil , and the error you've mentioned). 发生您提到的错误,因为没有一个注释设置user (这会导致对nil first_name调用,以及您提到的错误)。

Try modifying your template as follows, to track the "problematic" comment: 尝试如下修改模板,以跟踪“问题”注释:

<% @recipe.comments.each do |comment| %>
  <p><%= comment.content %><p>
  <% if comment.user.nil? %>
    Anonymous
  <% else %>
    <%= comment.user.first_name %>
  <% end %>
<% end %>

Hope that helps! 希望有帮助!

Update 更新

Try updating RecipesController : 尝试更新RecipesController

class RecipesController < ApplicationController
  def show
    @comment = Comment.new
  end
end

And replace @recipe.comments.build in partial: 并部分替换@recipe.comments.build

<div class="container">
  <% if user_signed_in? %>
    <%= form_for([@recipe.user, @recipe, @comment]) do |f| %>
      <%= f.label :content %><br>
      <%= f.text_area :content %><br>
      <br>
      <%= f.submit class: "btn btn-default" %>
    <% end %>
  <% end %>
</div>

You don't need "linking" @recipe and Comment at that point, as it will be properly handled in CommentsController#create . 此时您不需要“链接” @recipeComment ,因为它将在CommentsController#create正确处理。

That was nice exercise! 那是很好的运动!

Technically, you never check if the current_user exists. 从技术上讲,您永远不会检查current_user存在。 So when you iterate in each comments, if a someone, who's not log in, posts a comment, the user will be nil. 因此,当您迭代每个评论时,如果未登录的某人发布评论,则该用户将为nil。

To prevents this error, you can add this Devise Helper in your controller : 为了防止出现此错误,您可以在控制器中添加以下Devise Helper:

class CommentsController < ApplicationController
  before_filter :authenticate_pro_user!

It will automaticaly redirect to the sign in view if someone try to access the comments controller. 如果有人尝试访问评论控制器,它将自动重定向到登录视图。

A better way to handle that is using delegation and allowing nil, let me explain 一种更好的处理方法是使用委派并允许nil,让我解释一下

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :recipe

  delegate :first_name, to: :user, prefix: true, allow_nil: true
end

This will create a method called user_first_name ( user is the prefix ), and allow_nil means if user doesn't exist return nil 这将创建一个名为user_first_name的方法( userprefix ), allow_nil表示如果用户不存在,则返回nil

The view code will be like this 查看代码将如下所示

<% @recipe.comments.each do |comment| %>
  <p><%= comment.content %><p>
  <p><%= comment.user_first_name %></p> # notice it's 1 dot
<% end %>

When the loop reaches a comment that doesn't have a user, it will return nil which will turn into an empty string, 当循环到达没有用户的注释时,它将返回nil ,这将变成一个空字符串,
While when the user exists, the comment will go ask the user to return it's first_name 当用户存在时,注释将要求用户返回其first_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM