anonn023432
anonn023432

Reputation: 3120

Check chained association existence in rails

I have a rails Model association setup where every User has_one Buyer and specific Users can register as a Seller as well (has_one association).

Also some of the buyers can be specified as Elite as another has_one relation to a Buyer.

Now I have a situation where I want to setup a cron job to check the activity of different buyers and exclude all sellers and elite buyers.

My method for the same is:

def self.create_daily_user_notifications
  @users = User.where({ banned: false, admin: false })
  @users = @users.reject {|u| u.seller or u.buyer.elite }
end

The problem in this situation is that if there is a condition where a buyer doesn't have an associated elite relation it actually gives an error undefined method elite for buyer.

I would guess it's because the join doesn't exist for situations where a buyer is not elite. Is there a way I can just add this check?

Upvotes: 0

Views: 31

Answers (1)

Pavan
Pavan

Reputation: 33542

Well, then you can use try to silence the error and proceed with the check.

@users = @users.reject {|u| u.seller or u.buyer.try(:elite) }

Upvotes: 2

Related Questions