确认 Rails 使用复选框设计用户

Confirm Rails Devise user with checkbox

在管理用户时,我希望管理员能够使用复选框确认用户的帐户以触发用户的设计 user.confirm 方法。

我最初认为我可以使用 attr_accessor 设置一个名为 confirm_now 的变量,用作用户表单上的布尔值,然后在控制器更新操作中(或通过 before/after 操作回调)评估布尔值并相应地确认用户。

我仍然不太确定我是否需要模型中的方法来设置和读取 attr_accessor 变量,我仍然在思考这个问题......或者我可能过度了 -使这个复杂化并且应该在单击保存时调用 user.confirm 方法(这是不好的做法吗? - 我犹豫是否将此字段添加到 user_params)。

型号:

class User < ApplicationRecord

  attr_accessor :confirm_now
...

控制器:

class UsersController < ApplicationController
...
  def update
    if params[:user][:password].blank?
      params[:user].delete(:password)
      params[:user].delete(:password_confirmation)
    end
    if !@user.confirmed? && @user.confirm_now
      @user.confirm
    end
...
  private

    def user_params
      params.require(:user).permit(:first_name, :last_name, :email, :password, :account_active, :confirm_now)
    end

表单片段 (这按预期进行评估和工作):

  <% if !@user.confirmed? %>                   
    <%= f.input :confirm_now, label: 'Confirm User', as: :boolean, checked_value: true, unchecked_value: false %>
  <% end %>

Rails Log (attr_accessor在表单上勾选时设置):

Processing by UsersController#update as HTML
  Parameters: {"authenticity_token"=>"...", "user"=>{"first_name"=>"gg", "last_name"=>"gg", "email"=>"gg@gg.com", "account_active"=>"1", "confirm_now"=>"true", "password"=>"[FILTERED]"}, "commit"=>"Save", "id"=>"45"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" =  ORDER BY "users"."first_name" ASC LIMIT   [["id", 1], ["LIMIT", 1]]
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" =  ORDER BY "users"."first_name" ASC LIMIT   [["id", 45], ["LIMIT", 1]]
  CACHE User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" =  ORDER BY "users"."first_name" ASC LIMIT   [["id", 45], ["LIMIT", 1]]
Redirected to http://localhost:3000/users
Completed 302 Found in 6ms (ActiveRecord: 0.6ms | Allocations: 2665)

提前致谢!

为了简化,我会把它做成一个按钮,然后直接传递 confirmed_at 字段。

参数白名单:

def user_params
  params.require(:user).permit(:first_name, :last_name, :email, :password, :account_active, :confirmed_at)
end

表格:

<%=
  if @user.confirmed?
    link_to 'Unconfirm user',
            user_path(@user, { user: { confirmed_at: nil } }),
            method: :patch        
  else
    link_to 'Confirm user',
            user_path(@user, { user: { confirmed_at: Time.current } }),
            method: :patch
  end 
%>

请根据您的路线调整 paths/method 类型。