rails:如何验证用户登录的是哪种类型?

时间:2013-11-26 15:14:44

标签: html css ruby-on-rails

我是编程的新生。这是我的解决方案,但它无法登录。总是显示'无效的电子邮件/密码组合'。如何修改我的代码?如果有一些好的网络来学习rails ? 谢谢

<% provide(:title, "Sign in") %>
  <h1>Sign in</h1>

    <div class="row">
      <div class="span6 offset3">
         <%= form_for(:session, url: sessions_path) do |f| %>
           <%= f.label :email %>
           <%= f.text_field :email %>
           <%= f.label :password %>
           <%= f.password_field :password %>
            <%= f.label :type %>
            <%= f.radio_button :type, 1, :checked => true %> Student
            <%= f.radio_button :type, 2 %> Teacher
            <%= f.submit "Sign in", class: "btn btn-large btn-primary" %>
          <% end %>
          <p>New students? <%= link_to "Sign up now!", signup_path %></p>
      </div>
    </div>

会话控制器:

class SessionsController < ApplicationController

  def new
  end

  def create
    if [:type] == 1
      user = User.find_by_email(params[:session][:email].downcase)
      if user && user.authenticate(params[:session][:password])
        redirect_to user
        #sign_in user
        # Sign the user in and redirect to the user's show page.
      else
        flash.now[:error] = 'Invalid email/password combination'
        render 'new'
      end
    else 
      teacher = Teacher.find_by_email(params[:session][:email].downcase)
      if user && user.authenticate(params[:session][:password])
        redirect_to teacher
        #sign_in user
        # Sign the user in and redirect to the user's show page.
      else
        flash.now[:error] = 'Invalid email/password combination'
        render 'new'
      end
    end 
  end

  def destroy
    sign_out
    redirect_to root_url
  end

  def signed_in_user
    unless signed_in?
      flash[:notice] = "Please sign in"
      redirect_to signin_url
    end
  end 
end

1 个答案:

答案 0 :(得分:1)

当从表单提交值时,您的控制器将在params哈希中将其作为字符串接收。你不是在调用params哈希。您还要针对整数进行测试,因此[:type] == 1始终返回false,因为您需要检查params[:type]"1"的{​​{1}}。

有很多铁道教程,但是一个好的起点是guides.rubyonrails.org的官方指南