activerecord存在总是返回false

时间:2017-06-29 17:00:13

标签: ruby-on-rails ruby

我正在检查我的数据库中是否存在记录,但即使它确实存在,它也会一直返回false。我尝试在rails的控制台中以及它返回true,但在我的应用程序中它不起作用我似乎无法找到原因? 更新(完整代码):

class FormulaireController < ApplicationController
  def index
    @accounts = Account.all
    @account = session[:logged] ? Account.find_by(username: session[:username]) : Account.new
  end

  def create
    if params[:loginbtn]
      if Account.exists?(account_params)
        @account            = Account.find_by(username: params[:username])
        session[:username]  = @account.username
        session[:logged]    = true
        redirect_to root_path, notice: "Hello, #{@account.username}! You successfully logged in!" and return
      else
        redirect_to root_path, notice: "Invalid username or password. Create a new account ?" and return
      end
    else
      @account = Account.new(account_params)
      if Account.exists?(:username => @account.username)
        redirect_to root_path, notice: "Username already taken !" and return
      elsif @account.save
        session[:username]  = @account.username
        session[:logged]    = true
        redirect_to root_path, notice: "Hello, #{@account.username}! You successfully created your account!" and return
      end
    end
    render 'index'
  end

  def logout
    if session[:logged]
      reset_session
      redirect_to root_path, notice: "Successfully logged out !" and return
    end
    render 'index'
  end

  private
    def account_params
      params.require(:account).permit(:username, :password)
    end
end

我知道这根本不安全,但这只是为了学习rails我是初学者。

继承人的形式:

<%= form_for @account, url: create_path, method: :post do |f| %>
    <div class="input-group col-xs-6">
      <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
      <%= f.text_field :username, class: "form-control" %>
    </div><br>
    <div class="input-group col-xs-6">
      <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
      <%= f.password_field :password, class: "form-control" %>
    </div><br>
    <div class="form-group">
      <% if session[:logged] %>
        <%= link_to "Disconnect", logout_path, class: "btn btn-primary" %>
      <% else %>
        <%= f.submit "Login", name: "loginbtn", class: "btn btn-primary" %>
      <% end %>
      <%= f.submit "Register", name: "registerbtn", class: "btn btn-success" %>
    </div>
  <% end %>

routes.rb中:

  Rails.application.routes.draw do

   root  :to        => 'formulaire#index'
   get   '/logout'  => 'formulaire#logout'
   post  '/create'  => 'formulaire#create'

  end

我手动检查params并返回正确的值,我也检查我的DB是否正确,但是当我使用存在时它会一直返回false?方法

更新(控制台日志):

    Started POST "/create" for 127.0.0.1 at 2017-06-29 19:29:27 +0200
    Processing by FormulaireController#create as HTML
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"ttElLyvYuuGY1noKEfT7Vqg7HY2sFJehi/ZgESRftjwbBzVQVS7uOKvEADbYiCuw9xJNIZGICrM36c9x2hWKCQ==", "account"=>{"username"=>"Henrygolant", "password"=>"[FILTERED]"}, "loginbtn"=>"Login"}
      Account Load (0.2ms)  SELECT  `accounts`.* FROM `accounts` WHERE `accounts`.`username` IS NULL LIMIT 1
    Redirected to http://localhost:3000/
    Completed 302 Found in 2ms (ActiveRecord: 0.2ms)

Started GET "/" for 127.0.0.1 at 2017-06-29 19:29:27 +0200
Processing by FormulaireController#index as HTML
  Rendering formulaire/index.html.erb within layouts/application
  Account Exists (0.2ms)  SELECT  1 AS one FROM `accounts` LIMIT 1
  Account Load (0.2ms)  SELECT `accounts`.* FROM `accounts`
  Rendered formulaire/index.html.erb within layouts/application (2.9ms)
Completed 200 OK in 28ms (Views: 26.7ms | ActiveRecord: 0.3ms)

2 个答案:

答案 0 :(得分:2)

  

我手动检查了参数并且它返回了正确的值,我也是   检查我的数据库是否正确,但在我使用时它会一直返回false   存在?方法

exists?方法要求 Integer / String / Array / Hash argument,但是您传递的account_params是{ActionController::Parameters的实例1}}。所以始终会返回false

似乎find_or_create_by可能最适合您要做的事情

答案 1 :(得分:0)

你应该这样做:

def create
  if params[:loginbtn]
    if @account = Account.find_by(username: params[:account][:username])
      session[:username]  = @account.username
      session[:logged]    = true
      redirect_to root_path, notice: "Hello, #{@account.username}! You successfully logged in!" and return
    else
      redirect_to root_path, notice: "Invalid username or password. Create a new account ?" and return
    end
  else
    @account = Account.new(account_params)
    if @account.save?
      session[:username]  = @account.username
      session[:logged]    = true
      redirect_to root_path, notice: "Hello, #{@account.username}! You successfully created your account!" and return
    else
      redirect_to root_path, notice: "Username already taken !" and return
    end
  end
  render 'index'  
end

如果是登录,如果@account为零(即找不到/不存在),那么您将转到您的其他声明。

在注册的情况下,如果@account.save失败(即因为已经使用了用户名而无效),那么你也会转到你的else语句。

另外,我不确定你需要:

elsif params[:registerbtn]

除非有其他方式提交表单。所以也许只是else

帕万的建议是一个很好的建议。在这种情况下,这可能会变成:

def create
  if @account = Account.find_or_create_by(account_params)
    session[:username]  = @account.username
    session[:logged]    = true
    redirect_to root_path, notice: "Hello, #{@account.username}! You successfully logged in!" and return
  else
    redirect_to root_path, notice: "Invalid username or password. Create a new account ?" and return
  end
  render 'index'  
end