首页 > 解决方案 > Rails将设计用户名设置为评论属性

问题描述

我是 Rails 新手,仍在弄清楚哪些东西属于模型,哪些属于控制器。我正在创建一个属于文章的简单评论模型。我有一个属性 :commenter ,它是一个字符串。我想从 current_user 获取用户名(我正在使用我的登录功能设计)我会在我的控制器的 create 方法中执行此操作吗?

就像是

def create
    @post = Post.find(params[:post_id])
    @comment.commenter = current_user.username
    @comment = @post.comments.create(comment_params)
    redirect_to post_path(@post)
end

标签: ruby-on-railspostgresqlactiverecorddevise

解决方案


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

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user #should have user_id: integer in Comment
  belongs_to :post #should have post_id: integer in comment
  delegate :username, to: :user, allow_nil: true
end

在帖子控制器中: -

    def create
      @post = Post.find(params[:post_id])
      @comment = @post.comments.new(comment_params)
      @comment.user = current_user
      if @comment.save
        flash[:success] = "Comment saved successfully!"
        redirect_to post_path(@post)
      else
        flash[:error] = @comment.errors.full_messages.to_sentence
        redirect_to post_path(@post)
      end
    end

之后,您可以获得任何评论的所有用户详细信息:-

comment = Comment.find(#id_of_comment)
comment.username => #will return username because of delegation

委托参考


推荐阅读