簡體   English   中英

如何防止模型更新更改屬性?

[英]How do I prevent model update from changing an attribute?

我有具有role Account模型。 enum role: [:user, :admin]角色編寫的enum role: [:user, :admin] 我希望如果只剩一個角色為admin帳戶,那么他不能將其角色更新為user 我認為需要寫這樣的東西: @account = Account.where(role: params[: role])...然后我不知道。

account.rb

class Account < ApplicationRecord
  enum role: [:user, :admin]
end

accounts_controller.rb

class AccountsController < ApplicationController
  def index
    @accounts = Account.all
  end
  def update
    @account = Account.find(params[:id])
    redirect_to accounts_path if account.update(role: params[:role])
  end
end

schema.rb

create_table "accounts", force: :cascade do |t|
  t.integer "role", default: 0
end

我認為您想要的是一個模型回調 before_update ,其作用類似於驗證。

class Account < ApplicationRecord
  enum role: [:user, :admin]

  before_update :insure_admin, if: -> { role == :admin && role_changed? }

  private
  def insure_admin
    errors.add(:role, "admin cannot switch to regular user")
  end
end

這樣可以防止account.update(role: params[:role])返回true,但是您可能希望處理控制器中的錯誤,例如:

class AccountsController < ApplicationController
  def index
    @accounts = Account.all
  end
  def update
    @account = Account.find(params[:id])
    if account.update(role: params[:role])
      redirect_to accounts_path 
    else
      redirect_to :back, flash: account.errors.full_messages
    end
  end
end

您可能還希望添加前端表單驗證,以在該帳戶已被保留的情況下不允許更改角色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM