當我使用attr_accessible
指定我的模型I中的哪些字段將會公開時,腳本/控制檯也是如此嗎?我的意思是我沒有指定的attr_accessible
不能通過控制檯訪問?attr_accessible in rails Active Record
10
A
回答
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
時,只能通過控制檯或網站界面訪問這些東西。
例如:假設你做name
和email
是attr_accessible
:
attr_accessible :name, :email
和冷落created_at
和updated_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
乾杯。
相關問題
- 1. Database Arnostic'或'Query in Rails 4.2 Active Record
- 2. Rails Active Record TimeZones
- 3. Active Record Validation Rails 4
- 4. 動態attr_accessible in rails
- 5. Rails 5 Active Record has_and_belongs_to_many
- 6. Active Record Rails查詢
- 7. Rails Active Record回撥
- 8. Rails 4 Active Record finder方法
- 9. rename_column and change_column in one for active record migration
- 10. Rails 4 Active Record登錄會話失敗
- 11. 帶Rails/Active Record的時間數據
- 12. Active Record .where.find_each
- 13. ACTIVE RECORD REGULAR EXPRESSION
- 14. 在Rails schema/Active Record中使用「BIGINT UNSIGNED」
- 15. Rails Active Record .where語句優化
- 16. Rails Active Record查找每10條記錄
- 17. Rails/Active Record .save!效率問題
- 18. Rails 3中加入的Active Record查詢
- 19. 表加入Rails中的Active Record
- 20. 需要Rails/Active Record多態關聯嗎?
- 21. 創建或覆蓋Rails Active Record宏
- 22. 刪除Rails中的Active Record錯誤3.1
- 23. Rails/Active Record has_and_belongs_to_many關聯 - 獲取記錄
- 24. Rails - 會話的Cookies或Active Record Store
- 25. Rails - Active Record加入3個表格
- 26. Rails 3中的Active Record並總結
- 27. 是否能把連接查詢到Rails的Active Record協會
- 28. 使用Castle Active Record的表前綴使用Castle Active Record
- 29. Ruby Active Record關係
- 30. MySQL Active Record問題