ruby-on-rails – 将邀请码添加到Devise

我正在为婚礼创建一个RSVP应用程序.为了消除随机人员从RSVP到事件,我想在邀请中包含一个代码(即“groombride2015”).我想将此字段添加注册中,除非此代码有效,否则不允许注册处理.我花了一整天的时间试图解决这个问题.

我最接近它的工作是使用这种方法http://wp.headynation.com/simple-invitation-access-code-using-rails-4-devise/

谁能帮我吗?

解决方法

我前几天刚刚实现了这一点,实际上非常简单.首先,您需要在Devise注册表单中添加一个允许的参数

应用程序/控制器/ application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :configure_permitted_parameters,if: :devise_controller?
  after_action :verify_authorized,unless: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(
        :username,:email,:password,:password_confirmation,:remember_me,:sign_up_code
    ) }
  end
end

这些参数不必完全匹配,但您需要确保您用于输入注册代码的任何表单字段与您在此处传递的名称相匹配.

现在使用代码属性的字段更新设计视图:

应用程序/视图/设计/注册/ new.html.erb

<%= form_for( resource,as: resource_name,url: registration_path(resource_name)) do |f| %>
  <!-- Your Other Form Stuff -->
  <%= f.text_field :sign_up_code %>
<% end %>

接下来,我们需要添加一个虚拟属性和一些验证:

应用程序/模型/ user.rb

class User < ActiveRecord::Base
  attr_accessor :sign_up_code
  validates :sign_up_code,on: :create,presence: true,inclusion: { in: ["your_code"] }
  # The rest of your model
end

现在你们都准备好了!

请注意,如果您想要表invite_codes中的动态邀请代码,您还可以执行以下操作:

包含:{in:proc {InviteCode.where(used:false).map(&:code)}}

在上面的模型中,我有一个字符串代码一个布尔值,用于确保邀请代码只能使用一次.

例如,我使用以下seed.rb代码填充数据库创建时的邀请代码

invite_codes = (0...50).map { { code: SecureRandom.hex(7),used: false } }
  invite_codes = invite_codes.uniq

  invite_codes.each do |invite_code|
    InviteCode.find_or_create_by!( invite_code )
  end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...