ruby-on-rails - 当管理员按下提交时如何将表值设置为 true
问题描述
我的网站上有一个评论系统,想为管理员发表的评论添加管理员签名。并非所有评论都是用户留下的,因为评论是由访问该网站的任何人使用论坛发表的,即使是普通用户和管理员用户。
如果admin
布尔值true
在用户表上,则用户被视为管理员。
评论.rb
class Comment < ApplicationRecord
belongs_to :commentable, polymorphic: true
has_many :comments, as: :commentable, dependent: :destroy
default_scope {order(created_at: :asc)}
attribute :nickname, :captcha => true
validates :body, presence: true, length: { minimum: 3, maximum: 300 }
validates :name, presence: true, length: { minimum: 2, maximum: 30 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 100 },
format: { with: VALID_EMAIL_REGEX }
end
评论控制器.rb
class CommentsController < ApplicationController
before_action :find_commentable
private
def comment_params
params.require(:comment).permit(:body, :email, :name, :admin_comment)
end
def find_commentable
@commentable = Comment.find_by_id(params[:comment_id]) if params[:comment_id]
@commentable = Post.friendly.find(params[:post_id]) if params[:post_id]
end
end
如何在帖子上留下评论:(呈现另一种形式来回复评论,<%= simple_form_for([comment, Comment.new]) do |f| %>
而不是使用。)
<%= simple_form_for([@post, Comment.new]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.input :body, :as => :text, input_html: { maxlength: 300 }, label: false, placeholder: "What are your thoughts?", class: "form-control", wrapper_html: { id: 'contactTextarea' } %>
<%= f.input :name, label: false, placeholder: "Name (required) - Just your first name is okay too!", class: "form-control" %>
<%= f.input :email, label: false, placeholder: "Email Address (required) - This is not displayed with the comment", class: "form-control" %>
<div class="form-group hidden">
<%= f.input :nickname, :hint => "leave this field blank!", class: "form-control" %>
</div>
<%= f.submit "Post Comment", class: "btn btn-success" %>
<% end %>
我尝试过的(在find_commentable
方法中):
@commentable = User.find_by_id(params[:user_id]) if params[:user_id]
和
@commentable = User.friendly.find(params[:user_id]) if params[:user_id]
在用户模型中,我建立了关系has_many :comments, as: :commentable
解决方案
我只是想知道 admin_comment 是否可以在管理员发表评论时自动变为真,而不必使用复选框。
删除复选框并before_create
在评论模型中设置并检查评论的所有者是否为管理员。例如:
app/models/comment.rb
class Comment < AR
belongs_to :user
before_create do
self.admin_comment = true if user.admin?
end
end
顺便说一句,您的代码存在漏洞,任何人都可以发送admin_comment
带有true
值的参数。
推荐阅读
- c - OpenACC 循环未矢量化/并行化:包含调用
- java - 创建一个等待所有 Schedulers.io() 完成的 Mockito 测试用例
- java - 以编程方式正确打开“设置”中的“关于设备”页面?
- sql - 如何计算内连接函数的结果
- python - 在 Django 中编辑验证错误
- angular - Angular 9:在构造函数运行之前检查组件模板
- c++ - std::sort() C++ 的自定义比较函数
- ruby-on-rails - ruby-on-rails 中的 Mongoid
- python - 熊猫“替换”方法无法替换点(。)字符
- flutter - Flutter Hero 动画不适用于 SliverAppBar