表单中的错误不在视图中显示

时间:2016-03-13 18:26:39

标签: ruby-on-rails ruby forms

我正在尝试在未正确提交表单时在我的视图中显示错误。我在我的模型中有一个验证集,用于存在位置,在我的表单中,我使用errors方法尝试在我的视图中显示错误。以下是我的代码。验证工作正常,因为当location为nil时我收到rails错误,它只是没有将msg显示为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

3 个答案:

答案 0 :(得分:1)

如果保存失败,

@destination.save!将抛出错误。要访问render new_path行,您只需@destination.save

答案 1 :(得分:1)

如果不成功,

@destination.save!会引发错误。

@destination.save将返回true或false。

答案 2 :(得分: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。

相关问题