我在铁路4的验证有问题吗?

时间:2016-04-28 03:32:20

标签: ruby-on-rails ruby

我想在“users.rb”中显示我的验证。任何人都可以帮忙吗?我看过一些视频教程然后发现自己不是“定义新的”,但我不知道如何解决这个问题。

user_controller.rb  
class UsersController::ApplicationController  
  def login    
    if params[:user] 
      @notice   = "LOGIN FAILED"
      @email    = params[:user][:mailaddress]
      @password = params[:user][:password]
      @user     = User.find_by(mailaddress: @email)

      if @user
        @member = Member.find_by(user_id: @user.id)
        if @member
          @hash = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), @member.salt, @password)
          if @hash == @member.hashed_password
            # SUCCESS
            @notice = "LOGIN SUCCESSFULL"
          end
        end
      end
    end 
  end
end
-------
user.rb

class User::ActiveRecord::Base
  has_one :member
  validates :mailaddress, presence: {message: "Email need inputed"} #want to show this validates in login.html.haml
end
---------------
login.html.haml

= form_for(:user, url:login_path) do |f|
  %div.login
    = f.label "Email", class:'control-label'
    = f.email_field :mailaddress, class: 'form-control'
    = f.label "Password", class: 'control-label'
    = f.password_field :password, class: 'control-label'
    %div.btn-are
      = f.submit 'Finish', class: 'btn'

1 个答案:

答案 0 :(得分:0)

验证仅适用于模型创建/更新,但不适用于某些操作(如登录)。

请参阅docs了解详情。

如果缺少一些参数,你可以显示flash

user_controller.rb  
class UsersController::ApplicationController  
  def login    
    if params[:user]
      unless params[:user][:mailaddress]
        flash[:error] = "Email is required"
        render :your_login_path
      end
      @notice   = "LOGIN FAILED"
      @email    = params[:user][:mailaddress]
      @password = params[:user][:password]
      @user     = User.find_by(mailaddress: @email)

      if @user
        @member = Member.find_by(user_id: @user.id)
        if @member
          @hash = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), @member.salt, @password)
          if @hash == @member.hashed_password
            # SUCCESS
            @notice = "LOGIN SUCCESSFULL"
          end
        end
      end
    end 
  end
end


- flash.each do |name, msg|
  = content_tag :div, msg, class: name

= form_for(:user, url:login_path) do |f|
 %div.login
   = f.label "Email", class:'control-label'
   = f.email_field :mailaddress, class: 'form-control'
   = f.label "Password", class: 'control-label'
   = f.password_field :password, class: 'control-label'
   %div.btn-are
    = f.submit 'Finish', class: 'btn'

上面的代码未经测试,但应该有效。

以下是flash documentation

但我强烈建议您使用devise来执行用户的sign_in / sign_up。