Rails教程语法&方法错误

时间:2014-04-05 20:14:40

标签: ruby-on-rails ruby-on-rails-4 railstutorial.org

可以使用一些帮助解决我遇到的跟踪rails教程的问题...我尝试以“访问者”访问用户索引时收到的第一个错误如下: (未登录的用户):

Showing /Users/user/Documents/production_app/app/views/users/_user.html.erb where line #3 raised:

undefined method `admin?' for nil:NilClass

我的原始代码:

_USER.HTML.ERB(USER PARTIAL)

<li>
  <%= link_to user.name, user %>
  <% if current_user.admin? && !current_user?(user) %>
    | <%= link_to "delete", user, method: :delete,
                              data: { confirm: "You sure?" } %>
  <% end %>
</li>

INDEX.HTML.ERB(USERS INDEX)

<% provide(:title, 'All users') %>
<h1>All users</h1>

<%= will_paginate %>

<ul class="users">
  <%= render @users %>
</ul>

<%= will_paginate %>

USERS CONTROLLER

class UsersController < ApplicationController
  before_action :signed_in_user,  only: [:edit, :update, :destroy]
  before_action :correct_user,    only: [:edit, :update]
  before_action :admin_user,      only: :destroy

  def index
    @users = User.paginate(page: params[:page], :per_page => 10)
  end

  def show
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      sign_in @user
      flash[:success] = "Welcome to the Production App!"
      redirect_to @user
    else
      render 'new'
    end 
  end

  def edit
    # @user = User.find(params[:id]) // section 9.14 REMOVED AS A RESULT OF THE NEW CORRECT_USER BEFORE FILTER
  end

  def update
    # @user = User.find(params[:id]) // section 9.14 REMOVED AS A RESULT OF THE NEW CORRECT_USER BEFORE FILTER
    if @user.update_attributes(user_params)
      # Handle a successful update
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted."
    redirect_to users_url
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password, :password_confirmation)
    end

    # Before filters

    def signed_in_user
      unless signed_in?
        store_location
        flash[:warning] = "Please sign in to access this page."
        redirect_to signin_url
      end
    end

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) unless current_user?(@user)
    end

    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end
end

会话控制器

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      # Sign in the user & redirect to users show page
      sign_in user
      redirect_back_or user
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  def destroy
    sign_out
    redirect_to root_url
  end
end

会话帮助

module SessionsHelper
  def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.hash(remember_token))
    self.current_user = user
  end

  def signed_in?
    !current_user.nil?
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user
    remember_token = User.hash(cookies[:remember_token])
    @current_user ||= User.find_by(remember_token: remember_token)
  end

  def current_user?(user)
    user == current_user
  end

  def sign_out
    current_user.update_attribute(:remember_token,
                                  User.hash(User.new_remember_token))
    cookies.delete(:remember_token)
    self.current_user = nil
  end

  def redirect_back_or(default)
    redirect_to(session[:return_to] || default)
    session.delete(:return_to)
  end

  def store_location
    session[:return_to] = request.url if request.get?
  end
end

用户模型

class User < ActiveRecord::Base
  before_save { self.email = email.downcase }
  before_create :create_remember_token

  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }

  has_secure_password
  validates :password, length: { minimum: 6 }

  def User.new_remember_token
    SecureRandom.urlsafe_base64
  end

  def User.hash(token)
    Digest::SHA1.hexdigest(token.to_s)
  end

  private

    def create_remember_token
      self.remember_token = User.hash(User.new_remember_token)
    end
end

现在......我从stackOverflow上的其他帖子了解到这种情况正在发生,因为访问者将admin用户设置为nil。然而,当我跟随几个人的建议时,它产生了一个新问题......我改变了:

<% if current_user.admin? && !current_user?(user) %>

从_user.html.erb部分到:

<% if current_user.try(:admin?) && !current_user?(user) %>

根据建议,现在我的错误如下:

/Users/user/Documents/production_app/app/views/users/_user.html.erb:9: syntax error, unexpected keyword_ensure, expecting keyword_end /Users/user/Documents/production_app/app/views/users/_user.html.erb:11: syntax error, unexpected end-of-input, expecting keyword_end

Extracted source (around line #7):

<ul class="users">
7  <%= render @users %>
</ul>

<%= will_paginate %>

我确定我错过了一些小/愚蠢的事情...我对你做错的任何指示都会非常感激......

感谢,

2 个答案:

答案 0 :(得分:1)

因为看起来用户部分意图在用户已登录的页面中呈现。您的current_usernil。在Ruby中,您无法在nil对象上调用方法。 因此,用户似乎没有登录。

答案 1 :(得分:1)

纯粹看原始代码,似乎只有在有管理员用户登录的情况下才会提供删除链接。

您收到undefined method 'admin?' for nil:NilClass错误,因为current_user为零;即没有用户登录。

如果没有为访问者提供删除链接,则可以通过以下方式轻松解决此问题:

<% if current_user && current_user.admin? && !current_user?(user) %>

即。在检查该用户是否为管理员之前,只需检查是否有current_user