2012-02-16 58 views
2

我需要访问模型的属性名称,但并未显示所有模型的属性名称。如何使用`attribute_names`方法在rails模型中访问attr_accessor

我有用户模型,我在其中添加了一个attr_accessor :color(因为我不想将它作为列存储在我的数据库中)。 但是,如果我尝试使用User.first.attribute_names来访问属性名称,它只显示数据库列,它没有显示'color'属性,那么我如何访问所有属性?是否有任何列出attr_accessor属性的方法?

回答

1

首先,如果你不知道在

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... 
-1

您是否试过#methods,即User.first.methods或User.accessible_attributes更符合您的需求。

2
User.accessible_attributes #will return array of accessible attributes 
+0

它返回零,我使用轨道2.3和红宝石1.8是一个问题? – 2012-02-16 09:43:33

+0

哦,我在阅读问题时错过了这个。 accessible_attributes将返回所有attr_accessable而不是att_accessor.posting另一个答案,因为在注释中的文本中不能格式化 – Naveed 2012-02-16 10:26:59

相关问题