Rails 3: Generate unique codes (coupons)

后端 未结 6 1188
借酒劲吻你
借酒劲吻你 2021-01-30 18:29

What\'s the best way to generate unique codes to use as coupon codes?

Thanks.

6条回答
  •  醉酒成梦
    2021-01-30 19:03

    You can do something like this too:

    chars = ('a'..'z').to_a + ('A'..'Z').to_a
    def String.random_alphanumeric(size=16)
        (0...size).collect { chars[Kernel.rand(chars.length)] }.join
    end
    

    But then you would have to compare against a database to make sure it is not used yet.

提交回复
热议问题