Rails:表单中的第一个参数不能包含 nil 或为空



有我的控制器文件belov。如您所见,我定义了创建、索引、显示和编辑方法。

class PeopleController < ApplicationController
before_action :authenticate_user!
#before_action :people_params
before_action :exist_or_not, except:[:show, :index, :edit]

def new
@person = Person.new
end
def show
@person = Person.find_by(id: params[:id])
end
def index
end
def edit
@person = Person.find_by(id: params[:id])
end

def update
@person = Person.find_by_id(params[:id])
if @person.update_attributes(people_params)
flash[:success] = 'person was updated!'
redirect_to person_edit_path
else
render 'edit'
end
end
def create
if Person.exists?(user_id: current_user.id)
flash[:warning] = 'you have already details!'
redirect_to root_path
else
@person = current_user.build_person(people_params)
if @person.save
flash[:success] = 'person was created!'
redirect_to root_path
else
render 'new'
end
end

end


private
def people_params
params.require(:person).permit(:gender, :birthday, :country_id,:country_name,:state_id, :lang, :id, :user_id)
end

def exist_or_not
if Person.exists?(user_id: current_user.id)
flash[:warning] = 'you have already details!'
redirect_to root_path
end
end
end

我也分享了我的 _form.html.erb 文件 belov。

<%= form_for @person do |f| %>

<div class="field">
<%= f.label :birthday %><br />
<%= f.date_select :birthday, :start_year=>1950, :end_year=>2005 %>
</div>
<div class="field">
<%= f.radio_button(:gender, "male") %>
<%= f.label(:gender_male,   "Male") %>
<%= f.radio_button(:gender, "female") %>
<%= f.label(:gender_female, "Female") %>
</div>
<div class="field">
<%= f.label :country_id %><br />
<%= f.collection_select :country_id, Country.order(:name), :id, :name, include_blank: true %>
</div>

<div class="field">
<%= f.label :state_id, "State or Province" %><br />
<%= f.grouped_collection_select :state_id, Country.order(:name), :states, :name, :id, :name, include_blank: true %>
</div>
<%= f.select :lang, collection: LanguageArray::AVAILABLE_LANGUAGES.sort.map {|k,v| [v,k]} %>

<div class="actions"><%= f.submit %></div>
<% end %>

问题是: 我可以创建和显示人物,但可以编辑。我无法打开编辑路径或页面。

"形式上的第一个参数不能包含 nil 或为空">

错误输出为:单击浏览器的错误输出

请帮助我解决此错误。 谢谢。

find_by

在未找到任何内容时返回nil,因此@personnil此错误。

对于对对象(如 show/edit/update/etc( 的操作,最好使用Person.find(params[:id]),当找不到对象时,它会引发ActiveRecord::RecordNotFound(稍后它将作为 http 错误 404 处理(。

至于为什么没有对象 - 检查 url 是否正确生成并且params[:id]包含相应的 id(例如,您可以将其他对象的 id 传递给 urlhelper,这会导致一个看起来正确的 url 无处可去(。

此外,您可能缺少要person_edit_path的参数

最新更新