我是铁杆的新手,还在弄清楚模型中属于哪些东西以及控制器中属于哪些东西。我正在创建一个属于文章的简单评论模型。我有一个属性: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
答案 0 :(得分:0)
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