簡體   English   中英

logging_in_user無法工作,無法繞過登錄用戶的登錄頁面

[英]logged_in_user not working bypassing landing page for logged in users

我已經看到了一些與此類似的帖子,但是它們似乎並不能解決我的問題。

問題它根本不起作用。 不會出錯,什么都不會,只是不進行評估,我也不知道為什么,因為它對其他事情有用嗎?

這是我的Welcome控制器定義:

  def show
    if logged_in?
      # raise  #I raise an error here and nothing happens on the web page. Just to confirm this isn't working for my sanity. 
      redirect_to recipes_url
    else
      render template: "welcome/#{params[:welcome]}"
    end
  end

函數login_in? 在我的/helpers/sessions_helper.rb中定義:

  def logged_in?
    !current_user.nil?
  end

這是current_user:

  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
    #  raise #The test still pass, so this branch is currently untested.
      user = User.find_by(id: user_id)
      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end

我的路線是:

 get 'welcome/:welcome' => 'welcome#show'
 root :to => 'welcome#home'

為什么不起作用? 無論我是否登錄,它都停留在歡迎頁面上。 我知道login_in嗎? 之所以正確評估,是因為頁面上還有其他基於此而動態的鏈接。

編輯:真正奇怪的是login_in嗎? 在我看來,僅在此控制器中有效。

這是應用程序布局視圖中的導航片段。

  <% if logged_in? %>
      <li><%= link_to "Profile", current_user %></li>
      <li><%= link_to "Log out", logout_path, method: "delete" %></li>
    <% else %>
      <li><%= link_to "Browse recipes", recipes_path %></li>
      <li><%= link_to "Log in", login_path %></li>
    <% end %>

最終站點的圖片

如果用戶已經登錄, logged_in_user實際上並沒有執行任何操作或不返回任何內容。它僅返回nil(其值為false),因此您的show操作甚至無法到達redirect_to recipes_url語句。

您打算使用logged_in? 功能? 提供logged_in? ,這應該可以工作logged_in? 顧名思義就是:

   def show
    if logged_in?
      redirect_to recipes_url
    else
      render template: "welcome/#{params[:welcome]}"
    end
  end

如果使用devise,請確保使用名為User的模型,並在routes.rb使用devise_for :users定義了routes.rb ,並在模型上聲明了devise_for :users ,至少包含以下內容:

 devise :database_authenticatable,
         :registerable,
         :rememberable,
         :validatable

好。 logging_in方法工作正常。 之所以不起作用,是因為我的路線是直接轉到視圖“ welcome#home”,並完全繞開了控制器。

一旦我將路線設置為“ welcome#show”,便可以使它正常工作。

謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM