2013-07-13 67 views
1

以前的軌道4,我在模型軌道4,使屬性不可訪問

class User < ActiveRecord::Base 
    attr_accessible :name, :email, :password, :password_confirmation 

    ... 
end 

但現在strong_parameters取代protected_attributes所以我評論它,並使用permit

現在我發現我可以在不允許的情況下訪問屬性。

rails c我能做到這一點:

2.0.0p247 :002 > User.new(admin: "1") 
=> #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil, remember_token: nil, admin: true> 

2.0.0p247 :016 > user = User.new(name: 'Nir', email: '[email protected]', password: 'foobar', password_confirmation: 'foobar', admin: "1") 
=> #<User id: nil, name: "Nir", email: "[email protected]", created_at: nil, updated_at: nil, password_digest: "$2a$10$xVnY8ydd5SoaLVipK5j4Del40FrOmu4bKypGjBEwvms7...", remember_token: nil, admin: true> 

當很明顯,我不應該能夠設置和更改管理屬性。只有user.toggle(:admin)應該可以。

那麼,我不理解或應該做的是正確的。 以及如何使這個測試通過:

describe "accessible attributes" do 
    it "should not have allow access to admin" do 
     expect do 
     User.new(admin: "1") 
     end.to raise_error(ActiveModel::MassAssignmentSecurity::Error) 
    end 
    end 

回答

1

爲了防止用戶設置admin屬性,則應其添加爲permit方法的參數。

params.require(:user).permit(:name, :whatever_else_you_allow) 

關鍵詞在此有:params(它涉及參數)和permit(你告訴Rails允許的屬性)。

Strong Parameters將使動作控制器參數被禁止在主動模型質量指定中使用,直到它們被列入白名單。在你的測試中,你直接在模型上設置屬性。沒有什麼能阻止你這樣做。

+0

我沒有'admin'而使用'permit'。這應該夠了嗎?有沒有辦法阻止直接設置屬性?如果是這樣,我需要使用它? – Nir

+0

這就夠了。 –