我可以使用Active Record Validations来验证用户创建的特定密钥吗?

时间:2014-02-20 10:52:33

标签: ruby-on-rails

例如,我的rails应用程序上有一个页面,用户可以创建一个帐户。我想使用密钥(或其他东西)来确保不只是任何用户创建帐户。

形式:

<h1>Create a user</h1>

<%= form_for @dashboard_user do |f|%>
    <% if @dashboard_user.errors.any? %>
     <div class="alert-error">
       <h2>Form is invalid</h2>
       <ul>
         <% for message in @dashboard_user.errors %>
          <li><%= message %></li>
         <% end %>
       </ul>
     </div>
    <% end %>

        <p>
          <%= f.label :email %><br />
          <%= f.text_field :email %>
        </p>

        <p>
          <%= f.label :password %><br />
          <%= f.password_field :password %>
        </p>

         <p>
           <%= f.label :password_confirmation %><br />
           <%= f.password_field :password_confirmation %>
         </p>
         <p>
           <%= f.label :validation_key %><br />
           <%= f.password_field :validation_key %>
         </p>
    <p class='button'><%= f.submit %></p>
<% end %>

用户模型:

class DashboardUser < ActiveRecord::Base
  attr_accessible :email,:password, :password_confirmation, :password_hash, :password_salt
  attr_accessor :password, :password_confirmation, :validation_key

  validates :password, :presence => true,
            :length => {within: 10..50},
            :confirmation => true

  validates :email, :presence => true,
            :uniqueness => true

我知道这不正确,但是像这样

  validates :validation_key, :presence => true,
            :is == 'SOME RANDOM KEY'

  before_save :encrypt_password

  def self.authenticate(email, password)
    dashboard_user = find_by_email(email)
    if dashboard_user && dashboard_user.password_hash == BCrypt::Engine.hash_secret(password, dashboard_user.password_salt)
      dashboard_user
    else
      nil?
    end
  end

  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash =BCrypt::Engine.hash_secret(password, password_salt)
    end
  end

end

2 个答案:

答案 0 :(得分:0)

使用

的验证格式
validates_format_of :validation_key, :with => /MYSTRING/i, :on => :create

答案 1 :(得分:0)

你可以试试这个:

validates :validation_key, inclusion: { in: %w(SOME RANDOM KEY) }