UptDogTT
UptDogTT

Reputation: 91

How does "empty?" work on Rails model objects?

How does Rails determine whether an instance of a model class is empty?

Let's say I have an instance of the Post model:

#<Post id: 14, related_id: 20999, related_type: "News", text: nil, created_at: "2012-09-01 04:32:27", updated_at: "2012-09-01 04:32:27">

The record is saved and is valid. But calling "empty?" on it will return true. What is Rails' criteria for determining the object is empty?

This is causing me problems because if I have a related model that uses:

validates_presence_of :post

The validation will fail if the related object is empty. I don't care that it's "empty?", though. As far as I'm concerned it's not truly empty and it's perfectly fine even though the text field is nil.

Upvotes: 0

Views: 375

Answers (1)

FedeX
FedeX

Reputation: 446

You should get "NoMethodError: undefined method `empty?' for Post" if you call empty? in any instance of your models because activerecord models doesn't define such method. You can find empty? method for example in Array, String, Hash but no in activerecord instances. Actually it's a Ruby method not Rails nor activerecord.

Sumarising, if you are able to do the following:

Post.new.empty?

or

Post.last.empty?

or

p = Post.last
p.empty?

That's wrong, it means that somewhere in your model you are defining the empty? method or including from somewhere else. So check your model. Hope this help you.

Upvotes: 1

Related Questions