我有一个简单的haml代码块使用" present?"确定对象是否具有属性:
- if @available_custom_content.present?
- @available_custom_content.each do |custom_content|
- if custom_content.button_image.present?
但我得到
"undefined method `button_image' for #<BulletinInsert:0x007ff0206f3520>
...不是&#34;在场?&#34;应该让我测试属性是否存在?
答案 0 :(得分:2)
present?
检查对象是否为nil
,但它没有假设对象上存在方法。在这种情况下,@available_custom_content
存在并代表BulletinInsert
类的实例,但该实例不定义了button_image
方法。
快速解决方案是在调用try
:button_image
时使用custom_content.try(:button_image)
方法,但这并不是一个好习惯。
是否有不同类型的自定义内容对象?最好在BulletinInsert
类上定义一个空方法,该方法在调用button_image
时不执行任何操作。或者创建一个CustomContent
类BulletinInsert
继承自包含空button_image
方法的类。
答案 1 :(得分:0)
所以button_image实际上是指一个mongoid关系:
has_mongoid_attached_file :button_image
我认为&#34;存在?&#34;方法无法处理......
我应该提一下,函数DOES可以处理具有关系的对象,但不处理那些没有关系的对象。
答案 2 :(得分:0)
正如kevinthompson所说,问题是@available_custom_content
没有button_image
方法。 present?
检查对象是nil
还是空:
nil.present? #=> false
"".present? #=> false
[].present? #=> false
{}.present? #=> false
false.present? #=> false
Object.new.present? #=> true
"foo".present? #=> true
[1,2,3].present? #=> true
{foo: :bar}.present? #=> true
true.present? #=> true
在这个特定情况下,可能需要db:migrate
。我假设BulletInsert
是Rails应用程序中的模型,通过将其称为“属性”的方式。
如果数据库中不存在该列,则undefined method <attribute_name>
是将被抛出的错误。这是因为Rails将在数据库中的所有列上定义访问器方法,这是允许您访问它们的方法。没有列,没有定义方法。