我需要訪問模型的屬性名稱,但並未顯示所有模型的屬性名稱。如何使用`attribute_names`方法在rails模型中訪問attr_accessor
我有用戶模型,我在其中添加了一個attr_accessor :color
(因爲我不想將它作爲列存儲在我的數據庫中)。 但是,如果我嘗試使用User.first.attribute_names
來訪問屬性名稱,它只顯示數據庫列,它沒有顯示'color'屬性,那麼我如何訪問所有屬性?是否有任何列出attr_accessor屬性的方法?
我需要訪問模型的屬性名稱,但並未顯示所有模型的屬性名稱。如何使用`attribute_names`方法在rails模型中訪問attr_accessor
我有用戶模型,我在其中添加了一個attr_accessor :color
(因爲我不想將它作爲列存儲在我的數據庫中)。 但是,如果我嘗試使用User.first.attribute_names
來訪問屬性名稱,它只顯示數據庫列,它沒有顯示'color'屬性,那麼我如何訪問所有屬性?是否有任何列出attr_accessor屬性的方法?
首先,如果你不知道在
How to iterate ActiveRecord Attributes, including attr_accessor methods
差的B/W attr_acessabe和attr_accessor看可以,如果你沒有一個屬性數據庫來保存再加入attr_accessor添加att_accessor到attr_accessable :)
attr_accessor :color
attr_accessible :color
現在
User.accessible_attributes # => ["color"], but beware that you have lost all other attribute you need to add those too if you want to enable mass assignment.
attr_accessible :color,:first_name,:blah,:blah...
您是否試過#methods,即User.first.methods或User.accessible_attributes更符合您的需求。
User.accessible_attributes #will return array of accessible attributes
它返回零,我使用軌道2.3和紅寶石1.8是一個問題? – 2012-02-16 09:43:33
哦,我在閱讀問題時錯過了這個。 accessible_attributes將返回所有attr_accessable而不是att_accessor.posting另一個答案,因爲在註釋中的文本中不能格式化 – Naveed 2012-02-16 10:26:59