pcasa
pcasa

Reputation: 3730

Ruby if Model.exists?

Have SubscriberList

When an order is placed I want to check if New User's email is all ready in our subscribers list.

If not, then add them. Problem is it adds them no matter what. Guess it's not performing check correctly.

Currently in my orders_controller I have

unless logged_in?
  @order.subscribe_after_purchase(@order.user.email)
end

And in my Order.rb I have

def subscribe_after_purchase(email)
   unless SubscriberList.exists?(email)
     SubscriberList.create(:email => email)
   end
end

Upvotes: 1

Views: 751

Answers (1)

John Topley
John Topley

Reputation: 115422

Try using:

unless SubscriberList.exists?(:email => email)
  SubscriberList.create(:email => email)
end

When you just pass the email address to the exists? method then ActiveRecord will interpret it as a primary key. Alternatively, you can use:

SubscriberList.find_or_create_by_email(email)

—which will have the same effect as your unless block; creating the record unless it already exists.

Upvotes: 2

Related Questions