下拉列表错误消息未显示

时间:2015-04-16 18:28:26

标签: ruby-on-rails render message

所以我有3个级联下拉和船型(brand_idyear_idmodel_id)。错误未显示。我添加了;

  validates :brand_id, presence: true
  validates :year_id, presence: true
  validates :model_id, presence: true
  validates :user_id, presence: true

#boat.rb。我有我的表格;

<%= form_for(@boat) do |f| %>
    <%= render 'shared/error_messages', object: f.object %>
      <div class="col-md-6">
      <%= f.label :Brand %>
      <%= f.collection_select(:brand_id,  @brands,  :id, :name, {:prompt   => "Select a Brand"}, {:id => 'brands_select'}) %>
    </div>
    <div class="col-md-6">
      <%= f.label :Year %>
      <%= f.collection_select(:year_id, @years, :id, :name, {:prompt   => "Select a Year"}, {:id => 'years_select'}) %>
       </div>
      <div class="col-md-6">
      <%= f.label :Model %>
      <%= f.collection_select(:model_id, @models, :id, :name, {:prompt   => "Select a Model"}, {:id => 'models_select'}) %>
     </div>
      <div class="col-md-6 col-md-offset-3">
      <%= f.submit "Next", class: "btn btn-primary"%>
     </div>
    <% end %>

我有shared/errors

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>
    <ul>
    <% object.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>

该共享错误消息非常适合用户模型。我的#create行动

def create
   @boat = current_user.boats.build(boat_params) if logged_in?
    if @boat.save
      flash[:success] = "Boat created!"
      redirect_to root_url
    else
      redirect_to new_boat_path(current_user) #returns here
    end
  end

我打电话给new.html并打开表格。当我按下而不选择任何内容时,它会重定向到new_boat_path(current_user)而不显示错误。我不知道为什么。

EDIT1: 这是日志:

Started GET "/boats/new.2" for 88.240.3.128 at 2015-04-16 21:58:01 +0000
Processing by BoatsController#new as 
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 2]]
  Rendered shared/_error_messages.html.erb (0.0ms)

所以它呈现但我没有在页面上看到任何错误

编辑2:#new方法(品牌,年份和型号是级联下拉列表,其中船模型有其ID)

def new
    @boat = Boat.new
    @brands  = Brand.all
    @years = Year.all
    @models   = Model.all
  end

1 个答案:

答案 0 :(得分:1)

您是redirectingnew_boat_pathnew操作会创建Boat的新实例,显然不会包含任何错误。

您可能想要做的是:

if @boat.save
  flash[:success] = "Boat created!"
  redirect_to root_url
else
  render 'new'
end

这不会执行重定向,只是呈现包含@boat变量的new视图,包括通过调用@boat.save创建的验证错误。