Ruby 在为类中的对象制作下拉菜单时为 nil:NilClass 提供未定义的方法"空?"



我正在制作一个 ruby on rails 应用程序,该应用程序具有部分形式,在新的 .html.erb 视图上呈现。它允许用户从下拉菜单中选择一个类别(电影所属),如下所示:

<%= simple_form_for @movie do |f| %>
<%= f.select :category_id, @categories %>
<%= f.input :title, label: "Movie Title" %>
<%= f.input :description %>
<%= f.input :director %>

这是电影控制器的一部分:

def new
@movie = Movie.new
@categories = Category.all.map{ |c| [c.name, c.id] }
end
def create
@movie = Movie.new(movie_params)
@movie.category_id = params[:category_id]
if @movie.save 
redirect_to movie_path(@movie)
else 
render 'new'
end
end

现在,每当创建电影时,我都会收到以下错误:

NoMethodError in Movies#create undefined method `empty?' for nil:NilClass`

显然,错误是在行上引发的:<%= f.select :category_id, @categories %>

现在,在我删除整个数据库中的所有记录之前,这已经起作用了(但是,类别都仍然存在),因此这可能与它有关。 谢谢。

当你用create方法编写render 'new'时,它只调用new.html.erb(或new.*,取决于你正在使用的模板引擎),而不是你new action。 因此,@categoriesnew.html.erbnil,因此抛出错误。

为了摆脱错误,创建一个私有方法来设置类别并调用它为新的和创建。

before_action :set_categories, only: [:new, :create]
def new
@movie = Movie.new
end
def create
@movie = Movie.new(movie_params)
@movie.category_id = params[:category_id]
if @movie.save 
redirect_to movie_path(@movie)
else 
render 'new'
end
end
private
def set_categories
@categories = Category.all.map{ |c| [c.name, c.id] }
end

相关内容

最新更新