處理attr_accessor
的導軌3.1部分顯然已損壞。Rails 3.1不能爲非數據庫模型批量分配受保護屬性
我有幾個模型根本沒有數據庫,有些模型的屬性沒有保留。
例子:
class User < ActiveRecord::Base
#persisted attribs
attr_accessible :name, :email, :password, :password_confirmation, :is_admin, :permissions
#non persisted attribs<br />
attr_accessor :roseburg, :kfc, :kcpl
........
,如果我試圖保存在控制器上創建的用戶或更新
def create<br />
@user = User.new(params[:user])
或
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
我得到一個錯誤類似Cannot mass assign protected attributes :roseburg, :kfc, :kcpl
解決方法是填充屬性並使用保存方法。
def create
@user = User.new
(params[:user]).each do |attr_name, attr_value|
if @user.respond_to?("#{attr_name}")
@user.send("#{attr_name}=", attr_value)
end
end
@user.save
.....
和
def update
@user = User.find(params[:id])
respond_to do |format|
(params[:user]).each do |attr_name, attr_value|
if @user.respond_to?("#{attr_name}")
@user.send("#{attr_name}=", attr_value)
end
end
if @user.save
....
我的問題是,這是否有安全有什麼影響?
如果我將它們添加到attr_accessible,Rails的嘗試將其保存到數據庫,並給了我的ActiveRecord :: UnknownAttributeError在UsersController#更新 – user1585163
如果我將它們添加到attr_accessible,Rails的嘗試將其保存到數據庫,並給了我 的ActiveRecord :: UsersController中的UnknownAttributeError#update 但是(在這裏發現)當我將它們添加到這兩個列表時......它可以很好地使用默認的新建(params [user])和更新。 去圖。 attr_accessible:姓名,:電子郵件:密碼:password_confirmation,:is_admin,:權限:羅斯堡,:肯德基,:kcpl attr_accessor:羅斯堡,:肯德基,:kcpl 這是沒有預料到,至少我或任何其他線程我已經搜索 – user1585163
很高興你整理出來!有趣... –