原谅我是Ruby的新手。我正试图创建一个包含动物园信息的网站。
我有一个enclosure
模型和一个animal
模型。
这是我在animal_controller
中的create
方法的代码
def create
if params.has_key?(:enclosure_id)
@enclosure = Enclosure.find(params[:enclosure_id])
@animal = Animal.new(animals_params)
@animal.user_id = current_user.id
if @animal.save
@enclosure.animals.push(@animal)
redirect_to enclosure_path(@enclosure)
else
# ????
end
else
@animal = Animal.new(animal_params)
@animal.user_id = current_user.id
if @animal.save
redirect_to @animal
else
render 'new'
end
end
end
然后我有两个地方可以创造一种新的动物。一种是在localhost:3000/animals/new
中使用表单。另一种是在特定外壳的show
页面上使用类似的形式,例如在localhost:3000/enclosures/1/
在上面的代码中,我检查enclosure_id
的存在,以确定呼叫的来源。如果找到了参数,我会立即将动物添加到围栏中。但是,如果@animal.save
失败,我不明白如何返回到传递验证错误消息的localhost:3000/enclosures/id
页面。在没有enclosure_id
的情况下,render 'new'
会将用户带回到../animal/new
页面,并传递错误消息。
感谢
我认为转到另一个页面不是一个好主意,因为您将不得不序列化链接到模型的错误,这将是复杂而丑陋的。
我认为你应该呈现附件的显示页面,然后显示错误
#....
if @animal.save
@enclosure.animals.push(@animal)
redirect_to enclosure_path(@enclosure)
else
render 'enclosures/show'
end
#....