当某人未登录但又已经有一个帐户但仍允许他们登录时,如何创建用户?

时间:2019-07-01 12:54:18

标签: ruby-on-rails devise

当某人访问该网站时,会在应用程序控制器中自动创建一个用户帐户:

  before_action :create_user

  def create_user
    unless current_user
      logger.info "Creating User"
      @user = User.new()
      @user.save
      sign_in @user
    end
  end

在sessions_controller.rb中,应跳过此操作:

  skip_before_action :create_user

要让人们登录,他们需要注销访客帐户,然后登录到其新帐户:

<%= link_to('login as another user', "javascript: logout(); signin();", :class => "dropdown-item") %>

function logout() {
  var xhr = new XMLHttpRequest();
  xhr.open("DELETE", `/users/sign_out`);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send();
}

function signin() {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", `/users/sign_in`);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send();
}

问题是,当有人单击“以其他用户身份登录”时,创建了一个新帐户:

Started DELETE "/users/sign_out" for 127.0.0.1 at 2019-07-01 16:21:54 +0200
Processing by Devise::SessionsController#destroy as HTML
  Parameters: {"authenticity_token"=>"rE1vsdcujWtmQLcmkkD7wqfDbnCgtXBffKTOs7WHQF34oK8DngKtigmTecnToqWMCkHw8qzdjESbnkAvTEEqwQ=="}
  User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 44], ["LIMIT", 1]]
   (0.5ms)  BEGIN
   (0.4ms)  COMMIT
Redirected to http://localhost:3000/users/sign_in
Completed 302 Found in 17ms (ActiveRecord: 1.6ms)

Started GET "/users/sign_in" for 127.0.0.1 at 2019-07-01 16:21:54 +0200
Processing by Devise::SessionsController#new as HTML
Creating User
   (0.4ms)  BEGIN
  SQL (3.3ms)  INSERT INTO "users" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id"  [["created_at", "2019-07-01 14:21:54.575423"], ["updated_at", "2019-07-01 14:21:54.575423"]]
   (24.2ms)  COMMIT
   (0.3ms)  BEGIN
  SQL (0.6ms)  UPDATE "users" SET "sign_in_count" = $1, "current_sign_in_at" = $2, "last_sign_in_at" = $3, "current_sign_in_ip" = $4, "last_sign_in_ip" = $5, "updated_at" = $6 WHERE "users"."id" = $7  [["sign_in_count", 1], ["current_sign_in_at", "2019-07-01 14:21:54.608076"], ["last_sign_in_at", "2019-07-01 14:21:54.608076"], ["current_sign_in_ip", "127.0.0.1"], ["last_sign_in_ip", "127.0.0.1"], ["updated_at", "2019-07-01 14:21:54.609110"], ["id", 45]]
   (0.5ms)  COMMIT
  Rendering devise/sessions/new.html.erb within layouts/application
  Rendered devise/shared/_links.html.erb (1.1ms)
  Rendered devise/sessions/new.html.erb within layouts/application (5.1ms)
Completed 200 OK in 73ms (Views: 28.4ms | ActiveRecord: 29.2ms)

编辑:

正如Deep和Sergio所建议的那样,我在route.rb中添加了它:

  devise_for :users, :controllers => {
    :sessions => "users/sessions"
  }

我不再在日志中看到“正在创建用户”。

但是我在sign_in页面上遇到此错误:

undefined method `login' for #<User:0x00007f4ef2e60468>

0 个答案:

没有答案