Clean up the validation code of stock
This commit is contained in:
parent
ea360dc028
commit
4e88be6562
5 changed files with 25 additions and 26 deletions
|
@ -86,9 +86,7 @@ class FormattedFormBuilder < ActionView::Helpers::FormBuilder
|
|||
def error_messages
|
||||
if object.errors.any?
|
||||
content_tag :div, class: "panel panel-danger form-errors" do
|
||||
content_tag(:div, class: "panel-body") do
|
||||
error_header + error_body
|
||||
end
|
||||
error_header + error_body
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -100,10 +98,12 @@ class FormattedFormBuilder < ActionView::Helpers::FormBuilder
|
|||
end
|
||||
|
||||
def error_body
|
||||
content_tag :ul do
|
||||
object.errors.full_messages.map do |msg|
|
||||
content_tag :li, msg
|
||||
end.join.html_safe
|
||||
content_tag(:div, class: "panel-body") do
|
||||
content_tag :ul do
|
||||
object.errors.full_messages.map do |msg|
|
||||
content_tag :li, msg
|
||||
end.join.html_safe
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -12,17 +12,6 @@ class Stock
|
|||
end
|
||||
end
|
||||
|
||||
validate :validate_stock_entries
|
||||
def validate_stock_entries
|
||||
stock_entries.each do |se|
|
||||
unless se.valid?
|
||||
se.errors.each do |_, e|
|
||||
errors[se.product.name] = "count " + e
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def update
|
||||
return false unless valid?
|
||||
|
||||
|
@ -31,6 +20,10 @@ class Stock
|
|||
end
|
||||
end
|
||||
|
||||
def valid?
|
||||
super && stock_entries.map(&:valid?).all?
|
||||
end
|
||||
|
||||
class StockEntry
|
||||
include ActiveModel::Model
|
||||
include ActiveModel::Validations
|
||||
|
|
|
@ -1,7 +0,0 @@
|
|||
<div class="row">
|
||||
<div class="col-md-6 col-md-offset-3">
|
||||
<%= form_for @stock do %>
|
||||
<%= submit_tag "Insert stock", class: 'btn btn-primary' %>
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
13
app/views/stocks/_errors.html.erb
Normal file
13
app/views/stocks/_errors.html.erb
Normal file
|
@ -0,0 +1,13 @@
|
|||
<% unless @stock.valid? %>
|
||||
<div class="panel panel-danger form-errors">
|
||||
<div class="panel-heading">
|
||||
<%= "#{pluralize(@stock.errors.count + @stock.stock_entries.map(&:errors).map(&:count).sum, "error")} prohibited this stock from being saved:" %>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<ul>
|
||||
<%= @stock.errors.full_messages.map{ |m| content_tag(:li, m) }.join.html_safe %>
|
||||
<%= @stock.stock_entries.map{ |se| se.errors.full_messages.map{ |e| "#{se.product.name}: #{e}" } }.flatten.map{ |m| content_tag(:li, m) }.join.html_safe %>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<% end %>
|
|
@ -2,7 +2,7 @@
|
|||
<div class="col-md-6 col-md-offset-3">
|
||||
<h2>Add stock</h2>
|
||||
<%= f_form_for @stock do |f| %>
|
||||
<%= f.error_messages %>
|
||||
<%= render 'stocks/errors' %>
|
||||
<%= f.fields_for :stock_entries do |se_field| %>
|
||||
<div class="row">
|
||||
<div class="col-sm-3">
|
||||
|
|
Loading…
Reference in a new issue