我用 devise 进行登录注册,生成一个 user 表,我又给 user 表添加了 username 这个字段。
----------------------------------小割一下------------------------------------------------------------------------
现在我用 acts_as_commentable 给 post 添加评论,按照 github 上步骤,我执行了一下步骤
rails g comment
rake db:migrate
在 post model 中添加了
class Post < ActiveRecord::Base
acts_as_commentable
end
model 的内容分别如下
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me, :username
validates :username, presence: true,
length: {maximum: 16},
uniqueness: true
end
post.rb
class Post < ActiveRecord::Base
acts_as_commentable
default_scope :order => 'id DESC'
attr_accessible :body, :title
end
comment.rb
class Comment < ActiveRecord::Base
include ActsAsCommentable::Comment
belongs_to :commentable, :polymorphic => true
default_scope :order => 'created_at ASC'
# NOTE: Comments belong to a user
belongs_to :user
validates :comment, :presence => true
attr_accessible :comment, :title
end
comment 的表单是这样写的
<% @comment ||= @post.comments.build %>
<%= form_for([@comment.commentable, @comment]) do |f| %>
<%= f.label :comment, "添加回应" %>
<%= f.text_area :comment %><br>
<%= f.submit %>
<% end -%>
comment 的 controller 是这样写的
def create
@comment = commentable_record.comments.create(params[:comment])
@comment.user = current_user #当前用户
respond_to do |format|
if @comment.save
format.html {redirect_to commentable_record, notice: '创建评论成功'}
format.json {render json: @comment, status: :created, location: commentable_record}
else
format.html { render action: :new }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
protected
def commentable_record
Post.find(params[:post_id])
end
end
最后我想在 view 中显示 comment 的内容和对应的 user 的用户名
<% @post.comments.each do |comment| %>
<%= comment.user %><br>
<%= comment.comment %><br>
<% end -%>
如果写成<%= comment.user %>好像显示的是 user 的对象,评论内容可以正常显示,如下图
如果改成<%= comment.user.username %> 则会提示错误:
请问该如何正确显示 user 表的内容比如 username,email 等