Search code examples
ruby-on-railsrubygemsuniquecoupon

Simple coupon generator in rails


I have working on this from quite a long time but didn't get anything useful, all i want to know is how to add a simple random coupon generator. I have a rails app where users can check offers of restaurant, salon etc now i want to add a system so that users can generate a coupon and show that coupon to avail offers.


Solution

  • You don't mention what sort of coupon format you require and I am sure there are a bunch of gems that do similar things. I guess one approach is to use a unique code that you can generate and then tag a user_id to the end of it to ensure uniqueness across many codes.

    def generate_coupon_code(user_id)
      characters = %w(A B C D E F G H J K L M P Q R T W X Y Z 1 2 3 4 5 6 7 8 9)
      code = ''
    
      4.times { code << characters.sample }
      code << user_id.to_s
    
      code
    end