在Rails中,保护模型属性通常涉及到数据验证、授权和数据加密。以下是一些建议和最佳实践:
validates
方法定义验证规则,例如:class User< ApplicationRecord
validates :email, presence: true, uniqueness: true
validates :age, numericality: { greater_than_or_equal_to: 18 }
end
before_action
方法在控制器中定义授权规则,例如:class UsersController< ApplicationController
before_action :authenticate_user!
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_action :check_permission, only: [:edit, :update, :destroy]
def show
end
def edit
end
def update
if @user.update(user_params)
redirect_to @user, notice: 'User was successfully updated.'
else
render :edit
end
end
def destroy
@user.destroy
redirect_to users_url, notice: 'User was successfully destroyed.'
end
private
def set_user
@user = User.find(params[:id])
end
def check_permission
unless current_user.admin? || current_user == @user
redirect_to root_path, alert: 'You are not authorized to perform this action.'
end
end
def user_params
params.require(:user).permit(:email, :age)
end
end
attr_encrypted
gem来实现数据加密,例如:gem 'attr_encrypted'
class User< ApplicationRecord
attr_encrypted :email, key: 'a secret key'
end
总之,保护Rails模型属性需要综合考虑数据验证、授权和数据加密,以确保数据的安全性和完整性。
领取专属 10元无门槛券
手把手带您无忧上云