2009-11-24 138 views
10

當我使用attr_accessible指定我的模型I中的哪些字段將會公開時,腳本/控制檯也是如此嗎?我的意思是我沒有指定的attr_accessible不能通過控制檯訪問?attr_accessible in rails Active Record

回答

19

這隻適用於質量分配。舉例來說,如果你要設置你的模型attr_protected :protected

>> Person.new(:protected => "test") 
=> #<Person protected: nil> 

相反,你可以設置你想要使用attr_accessible作爲訪問的所有屬性。

然而,下面還是將工作:

>> person = Person.new 
=> #<Person protected: nil> 
>> person.protected = "test" 
=> #<Person protected: "test"> 

這是相同的行爲控制器,視圖等attr_protected只能預防的變量質量分配,主要是從表格等

7

我找到了原因:

指定可以通過大規模分配設定模型的屬性,如new(attributes)update_attributes(attributes),或attributes=(attributes)的白名單。 這是attr_protected宏觀相反:

Mass-assignment will only set attributes in this list, to assign to the rest of 
attributes you can use direct writer methods. This is meant to protect sensitive 
attributes from being overwritten by malicious users tampering with URLs or forms. 
If you‘d rather start from an all-open default and restrict attributes as needed, 
have a look at `attr_protected`. 

因此,這意味着,它只是避免大規模分配,但我仍然可以設置一個值。

7

控制檯的行爲與您的Rails應用程序完全相同。如果您保護了特定模型的某些屬性,則無法從控制檯或從Rails應用程序本身批量分配這些屬性。

1

當您指定某些東西爲attr_accessible時,只能通過控制檯或網站界面訪問這些東西。

例如:假設你做nameemailattr_accessible

attr_accessible :name, :email 

和冷落created_atupdated_at(這你應該)。 然後,您只能在控制檯中編輯/更新這些字段。

0

如果要公開場形成你的模型,你可以使用

attr_accessor :meth # for getter and setters 
attr_writer :meth # for setters 
attr_reader :meth # for getters 

,或者如果你想添加一些行爲,你的屬性,你就必須使用虛擬屬性

def meth=(args) 
... 
end 
def meth 
... 
end 

乾杯。