如果一个用户行不存在,如何创建用户行,而不是用函数create()创建用户行

时间:2017-07-21 10:33:09

标签: ruby-on-rails

这是我的代码,对ldap进行身份验证,然后检查我的sql DB中是否有ldap user

class SessionsController < ApplicationController
  # require 'byebug'
  def create
    username = params[:nome]
    password = params[:password]

byebug
    if AuthenticateUser.new(username, password).call
      # user = User.create_with(NumeroEmpregado: number)
      # user.save
      # user2 = User.find_or_create_by(nome: username)
      user = User.where("nome = '#{username}'").first
        if user.present?
          session[:user_id] = user.id
          redirect_to '/'
        else 
            user = User.new({NumeroEmpregado: "999", nome: username})
      user.save
          session[:user_id] = user.id
          redirect_to '/'
        end
    else
      flash[:error] = "Erro!              \nNúmero de Empregado e/ou password incorrecto(a)"
      redirect_to '/login'
     end
  end
end

user = User.create无效,User.where在没有用户在场时返回用户,我的代码出了什么问题?我已经完成了此代码的各种迭代,但似乎都没有工作,并在行user.save中得到以下错误

  

SessionsController #create中的ActiveRecord :: StatementInvalid   TinyTds ::错误:写入服务器失败:BEGIN TRANSACTION

完整跟踪错误:

activerecord-sqlserver-adapter (5.0.7) lib/active_record/connection_adapters/sqlserver/database_statements.rb:278:in `execute'
activerecord-sqlserver-adapter (5.0.7) lib/active_record/connection_adapters/sqlserver/database_statements.rb:278:in `raw_connection_do'
activerecord-sqlserver-adapter (5.0.7) lib/active_record/connection_adapters/sqlserver/database_statements.rb:219:in `block in do_execute'
activerecord (5.0.3) lib/active_record/connection_adapters/abstract_adapter.rb:590:in `block in log'
activesupport (5.0.3) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activerecord (5.0.3) lib/active_record/connection_adapters/abstract_adapter.rb:583:in `log'
activerecord-sqlserver-adapter (5.0.7) lib/active_record/connection_adapters/sqlserver/database_statements.rb:219:in `do_execute'
activerecord-sqlserver-adapter (5.0.7) lib/active_record/connection_adapters/sqlserver/database_statements.rb:45:in `begin_db_transaction'
activerecord (5.0.3) lib/active_record/connection_adapters/abstract/transaction.rb:133:in `initialize'
activerecord (5.0.3) lib/active_record/connection_adapters/abstract/transaction.rb:158:in `new'
activerecord (5.0.3) lib/active_record/connection_adapters/abstract/transaction.rb:158:in `begin_transaction'
activerecord (5.0.3) lib/active_record/connection_adapters/abstract/transaction.rb:188:in `within_new_transaction'
activerecord (5.0.3) lib/active_record/connection_adapters/abstract/database_statements.rb:232:in `transaction'
activerecord (5.0.3) lib/active_record/transactions.rb:211:in `transaction'
activerecord (5.0.3) lib/active_record/transactions.rb:392:in `with_transaction_returning_status'
activerecord (5.0.3) lib/active_record/transactions.rb:319:in `block in save'
activerecord (5.0.3) lib/active_record/transactions.rb:334:in `rollback_active_record_state!'
activerecord (5.0.3) lib/active_record/transactions.rb:318:in `save'
activerecord (5.0.3) lib/active_record/suppressor.rb:41:in `save'
app/controllers/sessions_controller.rb:22:in `create'
actionpack (5.0.3) lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action'
actionpack (5.0.3) lib/abstract_controller/base.rb:188:in `process_action'
actionpack (5.0.3) lib/action_controller/metal/rendering.rb:30:in `process_action'
actionpack (5.0.3) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
activesupport (5.0.3) lib/active_support/callbacks.rb:126:in `call'
activesupport (5.0.3) lib/active_support/callbacks.rb:126:in `call'
activesupport (5.0.3) lib/active_support/callbacks.rb:506:in `block (2 levels) in compile'
activesupport (5.0.3) lib/active_support/callbacks.rb:455:in `call'
activesupport (5.0.3) lib/active_support/callbacks.rb:455:in `call'
activesupport (5.0.3) lib/active_support/callbacks.rb:101:in `__run_callbacks__'
activesupport (5.0.3) lib/active_support/callbacks.rb:750:in `_run_process_action_callbacks'
activesupport (5.0.3) lib/active_support/callbacks.rb:90:in `run_callbacks'
actionpack (5.0.3) lib/abstract_controller/callbacks.rb:19:in `process_action'
actionpack (5.0.3) lib/action_controller/metal/rescue.rb:20:in `process_action'
actionpack (5.0.3) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
activesupport (5.0.3) lib/active_support/notifications.rb:164:in `block in instrument'
activesupport (5.0.3) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (5.0.3) lib/active_support/notifications.rb:164:in `instrument'
actionpack (5.0.3) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
actionpack (5.0.3) lib/action_controller/metal/params_wrapper.rb:248:in `process_action'
activerecord (5.0.3) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
actionpack (5.0.3) lib/abstract_controller/base.rb:126:in `process'
actionview (5.0.3) lib/action_view/rendering.rb:30:in `process'
actionpack (5.0.3) lib/action_controller/metal.rb:190:in `dispatch'
actionpack (5.0.3) lib/action_controller/metal.rb:262:in `dispatch'
actionpack (5.0.3) lib/action_dispatch/routing/route_set.rb:50:in `dispatch'
actionpack (5.0.3) lib/action_dispatch/routing/route_set.rb:32:in `serve'
actionpack (5.0.3) lib/action_dispatch/journey/router.rb:39:in `block in serve'
actionpack (5.0.3) lib/action_dispatch/journey/router.rb:26:in `each'
actionpack (5.0.3) lib/action_dispatch/journey/router.rb:26:in `serve'
actionpack (5.0.3) lib/action_dispatch/routing/route_set.rb:725:in `call'
rack (2.0.3) lib/rack/etag.rb:25:in `call'
rack (2.0.3) lib/rack/conditional_get.rb:38:in `call'
rack (2.0.3) lib/rack/head.rb:12:in `call'
rack (2.0.3) lib/rack/session/abstract/id.rb:232:in `context'
rack (2.0.3) lib/rack/session/abstract/id.rb:226:in `call'
actionpack (5.0.3) lib/action_dispatch/middleware/cookies.rb:613:in `call'
activerecord (5.0.3) lib/active_record/migration.rb:553:in `call'
actionpack (5.0.3) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call'
activesupport (5.0.3) lib/active_support/callbacks.rb:97:in `__run_callbacks__'
activesupport (5.0.3) lib/active_support/callbacks.rb:750:in `_run_call_callbacks'
activesupport (5.0.3) lib/active_support/callbacks.rb:90:in `run_callbacks'
actionpack (5.0.3) lib/action_dispatch/middleware/callbacks.rb:36:in `call'
actionpack (5.0.3) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.0.3) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
actionpack (5.0.3) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call'
web-console (3.5.1) lib/web_console/middleware.rb:135:in `call_app'
web-console (3.5.1) lib/web_console/middleware.rb:28:in `block in call'
web-console (3.5.1) lib/web_console/middleware.rb:18:in `catch'
web-console (3.5.1) lib/web_console/middleware.rb:18:in `call'
actionpack (5.0.3) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
railties (5.0.3) lib/rails/rack/logger.rb:36:in `call_app'
railties (5.0.3) lib/rails/rack/logger.rb:24:in `block in call'
activesupport (5.0.3) lib/active_support/tagged_logging.rb:69:in `block in tagged'
activesupport (5.0.3) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (5.0.3) lib/active_support/tagged_logging.rb:69:in `tagged'
railties (5.0.3) lib/rails/rack/logger.rb:24:in `call'
sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (5.0.3) lib/action_dispatch/middleware/request_id.rb:24:in `call'
rack (2.0.3) lib/rack/method_override.rb:22:in `call'
rack (2.0.3) lib/rack/runtime.rb:22:in `call'
activesupport (5.0.3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
actionpack (5.0.3) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.0.3) lib/action_dispatch/middleware/static.rb:136:in `call'
rack (2.0.3) lib/rack/sendfile.rb:111:in `call'
railties (5.0.3) lib/rails/engine.rb:522:in `call'
puma (3.9.1) lib/puma/configuration.rb:224:in `call'
puma (3.9.1) lib/puma/server.rb:602:in `handle_request'
puma (3.9.1) lib/puma/server.rb:435:in `process_client'
puma (3.9.1) lib/puma/server.rb:299:in `block in run'
puma (3.9.1) lib/puma/thread_pool.rb:120:in `call'
puma (3.9.1) lib/puma/thread_pool.rb:120:in `block in spawn_thread'

在我的rails控制台中,它只是说开始事务并给我同样的错误:

irb(main):004:0> username = "nogger"
=> "nogger"
irb(main):005:0> user = User.new({NumeroEmpregado: "999", nome: username})
  SQL (0.0ms)  USE [sqlserverapp]
=> #<User id: nil, NumeroEmpregado: "999", nome: "nogger", password_digest: nil, created_at: nil, updated_at: nil>
irb(main):006:0>           user.save
  SQL (0.0ms)  BEGIN TRANSACTION

      SQL (1.0ms)  USE [sqlserverapp]
  User Exists (1.0ms)  EXEC sp_executesql N'SELECT  1 AS one FROM [users] WHERE [users].[NumeroEmpregado] = @0 COLLATE Latin1_General_CS_AS_WS   ORDER BY [users].[id] ASC OFFSET 0 ROWS FETCH NEXT @1 ROWS ONLY', N'@0 nvarchar(max), @1 int', @0 = N'999', @1 = 1  [["NumeroEmpregado", nil], ["LIMIT", nil]]
=> false

user model:

class User < ApplicationRecord
has_secure_password
has_many :sheets
has_many :tarefa
has_many :estatisticas

validates :NumeroEmpregado, uniqueness:true


end

迁移:

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :NumeroEmpregado
      t.string :nome
      t.string :password_digest

      t.timestamps
    end
  end
end

2 个答案:

答案 0 :(得分:3)

来自评论中的来回:看起来唯一性验证行创建了无效的SQL语句。尝试删除整行。如果这有帮助,我们可以继续说明为什么会发生这种情况。

更多建议:

您应该使用find_by(:nome, username)代替where

where将始终返回非零值(ActiveRecord::Relation),您需要致电first,而find_by将返回Usernil

然后你不应该将参数插入到SQL查询中(代码的"'#{username}'"部分)。这很危险,允许SQL注入或参数破坏您的代码。

然后,如果创建失败,您可以使用create!引发异常(并且您需要挽救该异常以处理错误情况)。或者您可以查看create来电的返回值。

使用snake_case在ruby中也很常见,因此您应该调用NumeroEmpregado属性numero_empregado

答案 1 :(得分:0)

尝试在新用户记录上设置密码。我发现你定义了

password = params[:password]

从未使用过它。