简体   繁体   English

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

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

Forgive me I'm new at Ruby. 请原谅我是Ruby的新手。 I am trying to create a site to contain information about a zoo. 我正在尝试创建一个站点,以包含有关动物园的信息。

I have an enclosure model and an animal model. 我有一个enclosure模型和一个animal模型。

This is my code for the create method in animal_controller 这是我在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

I then have two places where a new animal can be created. 然后,我在两个地方可以创建新动物。 One is using a form at localhost:3000/animals/new . 一种是在localhost:3000/animals/new使用表单。 The other is using a similar form on the show page of a particular enclosure, so for example at localhost:3000/enclosures/1/ 另一种方法是在特定机箱的show页面上使用类似的形式,例如,在localhost:3000/enclosures/1/

In my code above, I check for the presence of enclosure_id to determine where the call is coming from. 在上面的代码中,我检查了是否发现了enclosure_id以确定调用来自何处。 If the parameter is found, I add the animal to the enclosure there and then. 如果找到该参数,则将动物添加到此处的外壳中。 However, if @animal.save fails, I do not understand how I can return to the localhost:3000/enclosures/id page with the validation error messages being passed. 但是,如果@animal.save失败,我将无法通过验证错误消息返回到localhost:3000/enclosures/id页面。 In the case of no enclosure_id , render 'new' takes the user back to the ../animal/new page with error messages passed as well. 如果没有enclosure_id ,则render 'new'使用户返回到../animal/new页面,同时传递错误消息。

Thanks 谢谢

I don't think it's a good idea to go to an other page, because you will have to serialize errors linked to the model and it's gonna be complicated and ugly. 我认为转到另一页不是一个好主意,因为您将不得不序列化与模型相关的错误,并且它会变得复杂而丑陋。

I think you should render the show page of the enclosure and then display the errors 我认为您应该呈现外壳的显示页面,然后显示错误

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