hel*_*llo 0 ruby ruby-on-rails railscasts ruby-on-rails-3
我正在关注RyanB的多态关联视频,该视频显示了实施评论系统的示例.
http://railscasts.com/episodes/154-polymorphic-association-revised?autoplay=true
我想知道如何将用户名添加到创建新评论的人的数据库中?这样我可以在视图页面中显示用户名,
谢谢
太多的方法来做到这一点
如果要对注释系统使用身份验证,则应添加一个模型用户进行身份验证(建议使用设计)
Run Code Online (Sandbox Code Playgroud)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
并在控制器上(取自154-多态关联 - 修订版的存储库)
Run Code Online (Sandbox Code Playgroud)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)class Comment < ActiveRecord::Base attr_accessible :content, :username belongs_to :commentable, polymorphic: true end
| 归档时间: |
|
| 查看次数: |
797 次 |
| 最近记录: |