ruby-on-rails - 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
解决方案
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
推荐阅读
- django - django-allauth 发送电子邮件时,电子邮件主题行中的“[Site]”
- javascript - 将项目添加到对象中的数组
- javascript - 右键单击上下文菜单像锚(打开新标签等)
- javascript - 使用值从数组中删除对象内容
- azure-active-directory - 使用访问令牌通过 Microsoft Graph API 与 OneDrive 交互
- linear-algebra - 获得所有旋转和反射矩阵组合的最便宜的方法是什么?
- python - 从 Dropbox 使用 discord.py 上传到 Discord
- google-cloud-platform - 如何知道剩余/使用的 Google Cloud Source Repository 存储?
- flutter - 有没有办法在riverpod的提供者中传递参数
- flutter - Flutter如何删除滚动条列表视图顶部的填充