如何在Rails中一次创建多个记录以获取优惠券代码

时间:2018-01-15 23:50:27

标签: ruby-on-rails activerecord

在我的应用中,用户应该能够创建一组x SecureRandom.hex(3)代码(用作优惠券)。我想要做的是向用户提供一个他可以输入数字的视图,例如: G。 200,然后应用程序创建200个不同的SecureRandom.hex(3)代码并将它们保存到数据库中。

我想我会在表单中添加一个数字字段,用户可以输入他想要的代码数量,然后将其作为参数传递给控制器​​。

我的问题是:我的创建操作应该如何实现应用程序然后创建200条SecureRandom.hex(3)代码记录?

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

def create
  count = params[:count].to_i
  return "Not a valid number" unless count.is_a?(Integer) && count.positive?

  count.times do 
    Coupon.create(code: SecureRandom.hex(3)) # or whatever your model name is
  end
end

但是,如果您在后台作业中创建所有优惠券以获得更好的性能,那就更好了。

答案 1 :(得分:0)

  1. 添加一个简单的优惠券模型,该模型将十六进制保存为属性。

  2. 为routes.rb

    中的操作添加新路由
    post '/coupons/create_multiple', to: 'coupons#create_multiple'
    
  3. 在您的控制器coupons_controller.rb

    中创建操作
    def create_multiple
      amount = params[:count].to_i
      if amount > 0
        amount.times do Coupon.create
      end
    end
    
  4. 在模型coupon.rb中执行“hex”-magic

    before_validation :generate_code
    protected
    def generate_code
        self.code = SecureRandom.hex(3)
    end
    
  5. 使用模型结构,您现在可以轻松添加验证,或者您可以添加更多属性来表示优惠券的状态。

    Btw:您应该给予全部限制,否则您必须将创建添加到后台作业中。