Ruby on Rails:railscasts评论系统:在评论数据库中插入用户名?

hel*_*llo 0 ruby ruby-on-rails railscasts ruby-on-rails-3

我正在关注RyanB的多态关联视频,该视频显示了实施评论系统的示例.

http://railscasts.com/episodes/154-polymorphic-association-revised?autoplay=true

我想知道如何将用户名添加到创建新评论的人的数据库中?这样我可以在视图页面中显示用户名,

谢谢

rai*_*_id 5

太多的方法来做到这一点

解决方案1

如果要对注释系统使用身份验证,则应添加一个模型用户进行身份验证(建议使用设计)

class User < ActiveRecord::Base
  attr_accessible :email, :password, :username
  has_many :comments
end


class Comment < ActiveRecord::Base
 attr_accessible :content, :user_id
 belongs_to :commentable, polymorphic: true
 belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

并在控制器上(取自154-多态关联 - 修订版的存储库)

def create
    @comment = @commentable.comments.new(params[:comment])
    @comment.user_id = current_user.id
    if @comment.save
     redirect_to @commentable, notice: "Comment created."
    else
     render :new
    end
end
Run Code Online (Sandbox Code Playgroud)

或解决方案2

您只需向评论模型添加一个属性(无需身份验证)

   class Comment < ActiveRecord::Base
     attr_accessible :content, :username
     belongs_to :commentable, polymorphic: true
   end
Run Code Online (Sandbox Code Playgroud)