簡體   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