grabury
grabury

Reputation: 5559

Equivalent: nil? and object not being set

Are these 2 code snippets equivalent if the user's subscription has not been set:

user.subscription.nil?

and

user.subscription

In the models: Subscription

belongs_to :user

User

has_one :subscription

Upvotes: 0

Views: 84

Answers (3)

Stefan
Stefan

Reputation: 114138

If you want to check that the association is not present, these are equivalent:

user.subscription.nil?     # true if missing, false otherwise
user.subscription.blank?   # true if missing, false otherwise
!user.subscription         # true if missing, false otherwise

And if you want to check that the association is present, these are equivalent (in terms of truthy and falsey):

user.subscription.present? # true if present, false otherwise
user.subscription          # subscription if present, nil otherwise
!!user.subscription        # true if present, false otherwise

Upvotes: 2

Bachan Smruty
Bachan Smruty

Reputation: 5734

In User model,

has_one :subscription

In Subscription model,

belongs_to :user

Here the association has been defined between users and subsriptions table i.e. one-to-one.

So in rails, we are dealing the records as object. SO once you have user record, you can get its associate objects. In this case user is a object of User class. So user.subscription returns the object of Subscription Class which contains the user_id equals to user.id .

And in some cases, there is no subscription for user. So we need to check before proceeding. That's why we are using user.subscription.nil? or user.subscription.blank? or user.subscription.present?. These are returning boolean.

Here if user is having a subscription, then user.subscription.nil? returns false and if user don't have subscription, then it returns true.

Upvotes: 1

sawa
sawa

Reputation: 168071

Not only that they are different, but they are almost the opposite. If the property is set to anything but nil, then the former will return false, and the latter will return whatever value. If the property is set to nil or is not set, then the former is true, the latter is nil. The only case when the two return the same value is when the property is set to false.

Upvotes: 1

Related Questions