Rails:nil的未定义方法`user':NilClass(ArticlesController#destroy中的NoMethodError)

时间:2016-09-11 20:44:46

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2

当我尝试删除我的应用程序中的文章时,我收到此错误,尽管用户和文章之间存在关联,并且当前用户已登录这里是我的代码

articles_controller.rb

class ArticlesController < ApplicationController
before_action :require_user , except:[:index,:show]
before_action :same_user , only: [:edit,:update,:destroy]

def index
    @articles = Article.all
end

def new
    @article = Article.new
end


def create
       @article = current_user.articles.build(article_params)

       if @article.save
           flash[:notice] = "Your Article was Created"
           redirect_to article_path(@article)
        else
           render 'new'
        end
    end

def show
    @article = Article.find(params[:id])
end

def edit
    @article = Article.find(params[:id])
end

def update
    @article = Article.find(params[:id])
    if @article.update(article_params)
        flash[:notice] = "Your Article was Updated"
        redirect_to article_path(@article)
    else
        render 'edit'
    end

end

def destroy
    @article = Article.find(params[:id])
    @article.destroy
    flash[:notice] = "Your Article was deleted"
    redirect_to articles_path(@article)
end

private

def article_params
    params.require(:article).permit(:title,:description, category_ids:[])
end

def same_user
    if current_user != @article.user and !current_user.admin?
        flash[:danger] = "Your are not allowed"
        redirect_to root_path
    end
end

_article.html.erb

    <% obj.each do |article|%>
<%= article.title%><br>
<%= article.description%>
<%= link_to "Show", article_path(article)%>
  <% if article.categories.any?%>
    <%= render article.categories%>
  <%end%>
<% if logged_in? && current_user == article.user || current_user.try(:admin?) # Another way to check for the user current_user.admin?
 %>
<%= link_to "Edit", edit_article_path(article)%>
<%= link_to "Delete", article_path(article), method: :delete, data: {confirm: "Really delete this article?"} %>
<%end%>
<small>Created By <%= article.user.email %></small>

<%end%>

application_controller.rb

  class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  helper_method :current_user , :logged_in?

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
end


  def logged_in?
    !!current_user
  end

  def require_user
    if !logged_in?
      flash[:danger] = "Please check your info"
      redirect_to articles_path
    end
  end

1 个答案:

答案 0 :(得分:1)

same_user方法中首先添加此行:

@article = Article.find(params[:id])

您应该在@article中定义same_user变量,因为您将此方法添加到before_action,此方法将在方法delete之前被移除。您尝试引用变量,后面定义了变量。