2016-03-13 37 views
0

我想在窗體未正確提交時顯示錯誤。我在我的模型中有一個驗證集以顯示位置,在我的窗體中我使用錯誤方法嘗試在我的視圖中顯示錯誤。以下是我的代碼。驗證工作正常,因爲當位置爲零時,我得到一個軌道錯誤,它只是不顯示爲HTML的味精。窗體中的錯誤不能顯示在視圖中

模型

class Destination < ActiveRecord::Base 
    validates :location, presence: true 
end 

形式new.html.erb

<%= form_for @destination do |f| %> 
    <% if @destination.errors.any? %> 
      <% @destination.errors.full_messages.each do |msg| %> 
       <li><%= msg %></li> 
      <% end %> 
    <% end %> 

    <%= f.label :location %> 
    <%= f.text_field :location %><br> 
    <%= f.submit %> 
<% end %> 

控制器

def create 
     @destination = Destination.new(destination_params) 

     if @destination.save! 
      redirect_to destinations_path 
     else 
      render new_path 
     end 
    end 

    private 

    def destination_params 
     params.require(:destination).permit(:location, :description) 
    end 
end 

回答

1

@destination.save!如果不成功會引發錯誤。

@destination.save將返回true或false。

1

@destination.save!將節省未果的情況下,拋出錯誤。要進入render new_path行,您只需要做@destination.save

0

@destination.save!會引發錯誤。你必須做一些事情;

if @destination.save # returns true if successfully saved else false 
    redirect_to destinations_path 
else 
    flash[:errors] = @destination.error_messages # Display errors in view 
    render new_path 
end 

HTH。

相關問題