ruby-on-rails - correct_user 不使用 current_user?

标签 ruby-on-rails ruby nomethoderror

我希望未登录的人能够看到展示页面。现在他们收到 current_userNoMethodError 错误。

def show
  @correct_user = current_user.challenges.find_by(id: params[:id])
end

sessions_helper

  # Returns the current logged-in user (if any).
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(:remember, cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

我使用 @correct_user 因为我只想向挑战的创建者展示某些东西:

<% if @correct_user %>
  # show stuff to user who made challenge  
<% else %>
  # show to everyone else, which would mean logged in users and non logged in users 
<% end %> 

除了 @correct_user 内的内容外,我如何允许未登录的用户看到显示页面?

最佳答案

这应该有助于检测 current_user 是否正确。

class UsersController < ApplicationController    
    before_action :set_challenge, only: :show
    before_action :check_user, only: :show

    private 

  def set_ challenge
     @challenge = Challenge.find(params[:id])
  end


    def check_user
      if current_user.id != @challenge.user_id
        redirect_to root_url, alert: "Sorry, You are not allowed to be here, Bye Bye ))"
      end
    end
end

关于ruby-on-rails - correct_user 不使用 current_user?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36437848/

相关文章:

ruby-on-rails - 事件记录 : ordering finds and also returning nulls

mysql - 从连接表访问数据

ruby-on-rails - 用户中的 NoMethodError #index 'undefined method ` each' for nil :NilClass'

javascript - 通过 Javascript 访问 ActionScript 函数

mysql - Pluck 查询正在运行,而 select 在 JOINS rails 查询中不起作用

ruby-on-rails - 配置 Ruby on Rails 以生成 .js 而不是 js.coffee

ruby-on-rails - 如何在 SSH 客户端(PuTTy)关闭后保持 Rails 控制台中的 rails 命令运行

ruby-on-rails - 为 ruby​​ 系统调用运行 eval ssh-agent

ruby - 通过比较 2 个相邻元素对数组进行分组