ruby-on-rails – 将邀请码添加到Devise
发布时间:2020-12-16 22:44:49 所属栏目:百科 来源:网络整理
导读:我正在为婚礼创建一个RSVP应用程序.为了消除随机人员从RSVP到事件,我想在邀请中包含一个代码(即“groombride2015”).我想将此字段添加到注册中,除非此代码有效,否则不允许注册处理.我花了一整天的时间试图解决这个问题. 我最接近它的工作是使用这种方法… ht
我正在为婚礼创建一个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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |