繁体   English   中英

Ruby重定向到同一页面,如果表单输入错误,则显示错误

[英]Ruby redirect to same page and show errors if form input is bad

请原谅我是Ruby的新手。 我正在尝试创建一个站点,以包含有关动物园的信息。

我有一个enclosure模型和一个animal模型。

这是我在animal_controller create方法的animal_controller

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
#....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM