开发者

Ruby if Model.exists?

开发者 https://www.devze.com 2023-01-09 22:23 出处:网络
开发者_Go百科Have SubscriberList When an order is placed I want to check if New User\'s email is all ready in our subscribers list.

开发者_Go百科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


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.

  • exists? API documentation
0

精彩评论

暂无评论...
验证码 换一张
取 消