首页 > 解决方案 > 当管理员按下提交时如何将表值设置为 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

标签: ruby-on-railsruby

解决方案


我只是想知道 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值的参数。


推荐阅读