【问题标题】:undefined method `model_name' for NilClass:Class, new actionNilClass:Class 的未定义方法“model_name”,新操作
【发布时间】:2013-05-15 13:17:17
【问题描述】:

我一直在尝试编辑默认脚手架,并且到目前为止非常成功。然而,这个小谜题让我感到困惑,因为即使将文件恢复到原始状态也不起作用。正如标题所暗示的那样,它为 NilClass:Class 抛出了一个“未定义的方法 `model_name'”。

用户控制器中的新操作:

def new
  if @current_user
    redirect_to(action: 'home')
  else
    @user = User.new
  end

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @user }
  end
end

_form.html.erb 开头

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from    being saved:</h2>

      <ul>
        <% @user.errors.full_messages.each do |msg| %>

任何帮助将不胜感激!

【问题讨论】:

  • 在哪一行?哪个文件?
  • @Mindbreaker _form.html.erb 的第一行。
  • 你有用户模型吗?或者你删除了它?
  • 我会尝试启动 Rails 控制台并执行 'user = User.new' 以确保模型按您认为的那样工作。
  • @Mattherick 用户模型存在。

标签: ruby-on-rails ruby


【解决方案1】:

在设置@current_user 的情况下,您的new 操作不会在redirect_to 之后停止执行。执行继续到respond_to 块,它尝试在 没有设置@user 的情况下呈现页面,从而导致您遇到错误。

可能的解决方案:

  1. 使用前过滤器 - 如果前过滤器触发重定向,则暂停当前操作的执行。这是标准的 Rails 实践。

    before_filter :check_for_current_user, only: [:new]
    
    def new
      @user = User.new
    
      respond_to do |format|
        format.html # new.html.erb
        format.json { render json: @user }
      end
    end
    
    protected
    
    def check_for_current_user
      redirect_to(action: 'home') if @current_user
    end
    
  2. 早点回来。

    def new
      if @current_user
        redirect_to(action: 'home') and return
      end
    
      @user = User.new
    
      respond_to do |format|
        format.html # new.html.erb
        format.json { render json: @user }
      end
    end
    

引用:http://excid3.com/blog/execution-after-redirect-vulnerability

【讨论】:

  • 感谢您的建议,但它似乎不起作用。我可能需要对模型做一些进一步的研究,因为目前没有任何操作有效......
猜你喜欢
  • 2011-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多