在实际使用的Rails 3中,它基于3.1,所以它有点旧,因为当我尝试分配admin而又没有使其免费进行大量分配时,我正在使用3.2.12,这会引发错误,并且那是因为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
而不在模型中添加上面的线
哪一个可以避免大规模分配,或者两者都是免费的?
双方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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句