繁体   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