帖子#show中的NoMethodError无法在评论中显示用户名

时间:2015-12-24 20:22:50

标签: ruby-on-rails ruby

<div class='comment'>
  <p>
    <%= comment.comment %>
    <%= comment.user.email %>
  </p>

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :user_name
      t.string :full_name
      t.string :email
      t.string :password_digest
      t.timestamps null: false
    end
  end
----------------------------------------------------------

class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.create(params[:comment].permit(:comment))
    @comment.user_id = current_user.id 
    @comment.save

    if @comment.save
      redirect_to post_path(@post)
    else
      render 'new'
    end
  end
end

    -------------------

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

    -------------------

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments
  validates :user, :presence => true
  validates :title, :presence => true, length: { maximum: 25}, uniqueness: true
  validates :content, :presence => true
end
    -------------------
class User < ActiveRecord::Base
  has_secure_password 

  has_many :posts
  has_many :comments

  def admin? 
    self.role == 'admin' 
  end

  def moderator? 
   self.role == 'moderator' 
  end

  validates :user_name,  :presence => true, uniqueness: true
  validates :full_name, :presence => true
  validates :password, :presence => true
  validates :email, :presence => true, uniqueness: true
end

     --------------------

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.text :comment
      t.references :post, index: true, foreign_key: true
      t.references :user, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

它说undefined method user_name

你可以说这些评论可能是在没有user_id的情况下创建的,但这不是真的,如果我写<%= comment.user_id %>它会显示正确的用户ID。此外,所有评论都有用户ID。 如果你可以请求帮助,因为我查了很多文档,但一无所获。

1 个答案:

答案 0 :(得分:1)

因为评论精华没有用户名,所以用户拥有它,所以你可以尝试像:

comment.user.user_name

或者更好的想法,添加:

delegate :user_name, to: :user

到您的评论模型,然后您也可以使用comment.user_name

你的变种: 1)将其添加到评论模型

  accepts_nested_attributes_for :user

2)在Comment控制器中为用户添加强大的属性(代码如params.require.permit):

  , user_attributes: %i(user_name full_name email password)

3)在你看来

  <%= fields_for :user, @comment.user do |user_fields| %>
    <% user_fields.text_field :user_name %>
    <% user_fields.text_field :full_name %>
    <% user_fields.text_field :email %>
    <% user_fields.text_field :password %>
  <% end %>

4)尽量保存它:)