Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 是什么导致nil:NilClass的未定义方法“map”?_Ruby On Rails_Ruby_Dictionary - Fatal编程技术网

Ruby on rails 是什么导致nil:NilClass的未定义方法“map”?

Ruby on rails 是什么导致nil:NilClass的未定义方法“map”?,ruby-on-rails,ruby,dictionary,Ruby On Rails,Ruby,Dictionary,我在控制器中定义了@categories #MoviesController def new @movie = current_user.movies.build @categories = Category.all.map {|c| [c.name, c.id] } end 在new.html.erb中 <%= simple_form_for @movie do |f| %> <%= select_tag(:category_id, options_

我在控制器中定义了@categories

#MoviesController
def new
    @movie = current_user.movies.build
    @categories = Category.all.map {|c| [c.name, c.id] }
  end
在new.html.erb中

<%= simple_form_for @movie do |f| %>
  <%= select_tag(:category_id, options_for_select(@categories), prompt: "Select a Category") %>
  <%= f.input :name %>
  <%= f.input :director %>
  <%= f.input :description %>
  <%= f.button :submit %>
<% end %>
当我提交创建新电影时,我得到一个错误,未定义nil:NilClass的方法“map”


在控制台中工作正常…

当您提交表单时,导航器将发出一个新的HTTP请求,并发送一个POST/movies,该请求将引导您创建MoviesController的方法。然后错误来自该方法。仔细检查您的创建方法

此外,我们通常在create方法中执行以下操作:

def create
  @movie = Movie.new(movie_params)

  if @movie.save
    redirect_to '/somewhere'
  else
    render :new
  end
end
如果是这样,则可以从create方法中渲染:new。问题是new.html.erb视图需要一个@categories变量,如果您使用的是create方法,则没有定义该变量。要解决这个问题,只需在createmethod中创建@categories变量:

你的问题没有带来足够的背景,所以我希望我发现了正确的问题,这肯定发生在moviescreate方法中,而不是moviesnew

如果创建操作有问题,则应显示创建代码。回溯也会有帮助。也就是说,我打赌你没有在create中设置@categories,这就是为什么当你的记录验证失败时它会崩溃。
def create
  @movie = Movie.new(movie_params)

  if @movie.save
    redirect_to '/somewhere'
  else
    @categories = Category.all.map { |c| [c.name, c.id] }
    render :new
  end
end