问题
So I have 3 cascading drop downs and a Boat Model (brand_id
, year_id
, model_id
). The errors are not shown. I have add;
validates :brand_id, presence: true
validates :year_id, presence: true
validates :model_id, presence: true
validates :user_id, presence: true
to #boat.rb
. I have my form;
<%= 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 %>
And I have the 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 %>
That shared error message works perfectly for user model. And my #create
action
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
I call the new.html and form opens. When I press without selecting anything it redirects to new_boat_path(current_user)
without showing errors. I dont know why.
EDIT1: Here is the log:
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)
So it renders but i do not see any errors on the page
EDIT 2: #new
method (brand, year & model are cascading drop down lists, where Boat model has their ids)
def new
@boat = Boat.new
@brands = Brand.all
@years = Year.all
@models = Model.all
end
回答1:
You are redirecting
to new_boat_path
. The new
action creates a new instance of Boat
which will obviously not contain any errors.
What you probably want to do is:
if @boat.save
flash[:success] = "Boat created!"
redirect_to root_url
else
render 'new'
end
This will not perform a redirect but just renders the new
view which contains the @boat variable including the validation errors created by calling @boat.save
.
来源:https://stackoverflow.com/questions/29683111/drop-down-list-error-message-not-shown