0

在 Rails 3 中,它基于 3.1,所以它有点旧,因为我使用 3.2.12,当我尝试分配 admin 而没有使其免费进行大规模分配时,它会引发错误,这是因为作者所说的 3.1 和 3.2 之间的差异. 所以最好使用以下哪个,有什么区别?

控制器中的第一种方法

  def create
    @user = User.new(params[:user], :as => :admin)
    if @user.save
        flash[:notice] = "User has been created."
        redirect_to admin_users_path
    else
        flash[:alert] = "User has not been created."
        render :action => "new"
    end
  end

在模型中

 attr_accessible :email, :password, :admin, :as => :admin

控制器中的第二种方法

   def create
    @user = User.new(params[:user], :without_protection => true)
    @user.admin = params[:user][:admin] == "1"
    if @user.save
        flash[:notice] = "User has been created."
        redirect_to admin_users_path
    else
        flash[:alert] = "User has not been created."
        render :action => "new"
    end
  end

没有在模型中添加上面的行

哪一个将防止大规模分配或两者都是免费的?

4

1 回答 1

1

两者attr_accessible:without_protection => true都可用于允许对定义它们的模型的属性进行批量分配。

所以最好使用以下哪个,有什么区别?

为了回答这个问题,我认为使用attr_accessible更好,因为您可以准确定义要允许批量分配的属性,而不是:without_protection => true打开模型中的所有属性进行批量分配。

:without_protection => true通常,如果您确切知道用​​户输入是什么,例如在播种数据时,传递是可以的。但是对于来自表单的输入(用户输入),您需要准确指定允许批量分配的内容。

希望这可以帮助。

更新:

在以下语句中,as您提供的选项attr_accessible确认email, password and admin仅当用户是 时才允许使用这些属性admin

attr_accessible :email, :password, :admin, :as => :admin
于 2013-09-01T15:46:52.647 回答