【问题标题】:Limiting which user attributes can be updated限制可以更新的用户属性
【发布时间】:2016-10-04 01:47:24
【问题描述】:

我不想让用户更新他们的:name。我找到了这个question for Rails version 3,但答案对我不起作用。我正在使用 Rails 4。我可能只是语法错误。我无法让@user.update_attributes(params[:user]) 工作。仅限:@user.update_attributes(user_params)。我的编辑表单中没有包含:name,但我的理解(??)是用户仍然可以自己通过浏览器传递它,并且使用我当前的代码他们可以更改:name

class UsersController < ApplicationController

def edit
  @user = User.find(params[:id])
end

def update
  @user = User.find(params[:id])
  @user.update_attributes(user_params)
    if @user.save
      flash[:success] = "Profile updated"
      redirect_to @user
    else 
      flash[:danger] = "Profile update Unsuccessful"
      redirect_to 'edit'
    end
end

private

def user_params
  params.require(:user).permit(:name, :email, :email_confirmation, :password, :password_confirmation)
end

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    有不止一种方法可以确保用户不会篡改您的业务规则。 由于您已经在使用 Rails 4,因此可以利用强参数来拒绝访问 :name 属性。

    您可以为每个控制器操作设置不同的规则集:

    def create_user_params
      params.require(:user).permit(:name,:email, :email_confirmation, :password, :password_confirmation)
    end
    
    def update_user_params
      params.require(:user).permit(:email, :email_confirmation, :password, :password_confirmation)
    end
    
    @user.create(create_user_params)
    @user.update_attributes(update_user_params)
    

    干涸:

    def allowed_update_attrs
     [:email, :email_confirmation, :password, :password_confirmation]
    end
    
    def allowed_create_attrs
     allowed_update_attrs + [:name]
    end
    
    def user_params
      params.require(:user)
    end
    
    @user.create user_params.permit(*allowed_create_attrs)
    @user.update_attributes user_params.permit(*allowed_update_attrs)
    

    还有其他方法可以完成同样的事情,比如利用已经允许的属性,但这种方法似乎更简单。

    【讨论】:

    • 我希望他们能够创建 :name 最初与 new/create... 我只是不希望他们能够 update/edit 他们的 :name 之后。跨度>
    • 感谢这项工作正确。有谁知道问题中链接的.except 是否仍然适用于 Rails 4?
    • @TimmyVonHeiss 我刚刚意识到Parameters 继承自ActiveSupport::HashWithIndifferentAccess,所以我之前的评论是错误的。 .except 应该可以工作。
    猜你喜欢
    • 1970-01-01
    • 2012-08-30
    • 2014-06-17
    • 1970-01-01
    • 2021-12-20
    • 2011-10-28
    • 2020-07-03
    • 2015-11-19
    • 2016-09-23
    相关资源
    最近更新 更多