【发布时间】:2009-11-10 18:09:18
【问题描述】:
我有一个方法需要遍历一个哈希并检查每个键是否存在于模型表中,否则它将删除键/值。
例如
number_hash = { :one => "one", :two => "two" }
并且 Number 表只有一个 :one 列,因此 :two 将被删除。
如何检查模型是否具有属性?
【问题讨论】:
标签: ruby-on-rails
我有一个方法需要遍历一个哈希并检查每个键是否存在于模型表中,否则它将删除键/值。
例如
number_hash = { :one => "one", :two => "two" }
并且 Number 表只有一个 :one 列,因此 :two 将被删除。
如何检查模型是否具有属性?
【问题讨论】:
标签: ruby-on-rails
一堂课
使用Class.column_names.include? attr_name,其中attr_name 是属性的字符串名称。
在这种情况下:Number.column_names.include? 'one'
举个例子
使用record.has_attribute?(:attr_name) 或record.has_attribute?('attr_name')(Rails 3.2+)或record.attributes.has_key? attr_name。
在这种情况下:number.has_attribute?(:one) 或 number.has_attribute?('one') 或 number.attributes.has_key? 'one'
【讨论】:
Hash#select:number_hash.select { |key, value| Number.column_names.include? key }
number.has_attribute? 接受符号或字符串
user 的模型,但由于某些模型委派了用户,因此不得不寻找 user_id。
Number.attribute_method? 'one'
record.try(:column_name) 如果列不存在则返回nil
如果您还需要检查别名,可以使用Number.method_defined? attr_name 或number.class.method_defined? attr_name。
我必须为具有别名字段的 Mongoid 对象执行此操作。
【讨论】:
ModelName.attribute_method? :attr_name 在我的实例中有效
在您的实例对象中,您也可以使用defined? instance.attribute 或instance.respond_to? :attribute。
这些是检查模型属性或任何方法的更通用的解决方案。
【讨论】:
instance.respond_to?(:attribute) == false ; instance.attribute ; instance.respond_to?(:attribute) == true
如果非常简化
模型列
记录列=属性
Model.columns Model.record.columns/attributes
列
检查模型的列是否存在
Foo.column_names.include? 'column_name'
记录是否存在该列?
foo.has_attribute?('column_name')
属性
检查模型的属性是否存在
Foo.attribute_method?(:attribute_name)
记录的属性是否存在?
foo.has_attribute?(:attribute_name)
方法
检查一个类的方法是否存在
Foo.method_defined?(:method_name)
该实例是否存在该方法?
foo.respond_to?(:method_name)
【讨论】: