I have read Rails 5 flash message not working with redirect_to but it is not concluding any solution after 2 years and 4 months and other topic related entries doesn't solve my problem so I'm posting this new question, I hope someone helps me solve the situation because it is quite frustrating not knowing what is wrong.
So, I have an app that logs licence periods (time off) for college members, my problem is that after a failed custom validation my form is not flashing the error message thus not letting the user know what was wrong with his previous attempt to save a new licence period.
The route I have defined for logging licence periods is:
resources :licencias, except: :new
get 'members/:member_id/licenciar' => 'licencias#new', as: :licenciar
So the licencias controller new action is called from the member#show partial with a link_to like this:
<%= link_to 'Agregar Licencias', licenciar_path(@member), class: "btn btn-in-table" %>
The licencias controller 'new' and 'create' actions are:
def new
@member = Member.find_by(id: params[:member_id])
@licencia = @member.licencias.new
end
def create
@member = Member.find_by(id: params[:licencia][:member_id])
@licencia = @member.licencias.build(licencia_params)
if @licencia.save
flash[:success] = "Se ha registrado exitosamente la Licencia."
redirect_to members_path
else
puts "******* @member.id: #{@member.id}"
puts "####### errors: #{@licencia.errors[:base]}"
flash.now[:danger] = @licencia.errors[:base]
redirect_to licenciar_url(@member)
end
end
Those 'puts' (old fashined debugging sorry) show this in Rails server logging
Started GET "/members/5/licenciar" for 127.0.0.1 at 2021-01-19 14:13:37 -0600
Processing by LicenciasController#new as HTML
Parameters: {"member_id"=>"5"}
Member Load (0.3ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? ORDER BY "members"."numero" ASC LIMIT ? [["id", 5], ["LIMIT", 1]]
? app/controllers/licencias_controller.rb:11
Rendering licencias/new.html.erb within layouts/application
Rendered shared/_error_messages.html.erb (0.9ms)
Rendered licencias/_form.html.erb (6.7ms)
Rendered licencias/new.html.erb within layouts/application (11.3ms)
Rendered layouts/_shim.html.erb (0.8ms)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
? app/helpers/sessions_helper.rb:10
Rendered layouts/_header.html.erb (6.4ms)
Rendered layouts/_footer.html.erb (1.5ms)
Completed 200 OK in 150ms (Views: 134.8ms | ActiveRecord: 0.7ms)
Started POST "/licencias" for 127.0.0.1 at 2021-01-19 14:13:55 -0600
Processing by LicenciasController#create as HTML
Parameters: {"utf8"=>"?", "authenticity_token"=>"ID18U67DeymDkwQ9FAfJiIgMKpdcZpmfjwU7FsFPH2mb6nOToIj+NGrHHg9M3/evN2UHrS0GHZjRCzDpZTkSJw==", "licencia"=>{"inicio"=>"2021-01-06", "final"=>"2021-01-10", "member_id"=>"5"}, "commit"=>"Guardar"}
Member Load (0.3ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? ORDER BY "members"."numero" ASC LIMIT ? [["id", 5], ["LIMIT", 1]]
? app/controllers/licencias_controller.rb:17
(0.2ms) begin transaction
? app/controllers/licencias_controller.rb:22
Member Load (0.3ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? ORDER BY "members"."numero" ASC LIMIT ? [["id", 5], ["LIMIT", 1]]
? app/models/validators/lapse_validator.rb:22
Licencia Exists (0.2ms) SELECT 1 AS one FROM "licencias" WHERE "licencias"."member_id" = ? LIMIT ? [["member_id", 5], ["LIMIT", 1]]
? app/models/validators/lapse_validator.rb:23
Licencia Load (0.3ms) SELECT "licencias".* FROM "licencias" WHERE "licencias"."member_id" = ? ORDER BY inicio ASC [["member_id", 5]]
? app/models/validators/lapse_validator.rb:24
(0.2ms) rollback transaction
? app/controllers/licencias_controller.rb:22
**
======= @member.id: 5
####### errors: ["El rango registrado se superpone con alguno de los períodos de licencia ya registrados. Verifique y corrija por favor."]
**
Redirected to http://localhost:3000/members/5/licenciar
Completed 302 Found in 37ms (ActiveRecord: 1.6ms)
This is the custom validation code:
class Validators::LapseValidator < ActiveModel::Validator
def validate(record)
licencias_activas = get_licences_array(record.member_id)
if licencias_activas.any?
lapse = { :inicio => record.inicio, :final => record.final }
error_found = lapse_validation(lapse, licencias_activas)
record.errors[:base] << "El rango registrado se superpone con alguno de los períodos de licencia ya registrados. Verifique y corrija por favor." unless error_found == 0
end
end
private
def get_licences_array(miembro)
arreglo = []
notario = Member.find(miembro)
if notario.licencias.any?
notario.licencias.each do|licencia|
arreglo << { :inicio => licencia.inicio, :final => licencia.final }
end
end
return arreglo
end
def lapse_validation(lapse, licencias)
found_error = 0
licencias.each do |span|
unless (lapse[:final] < span[:inicio] || lapse[:inicio] > span[:final])
found_error = 1
break
end
end
return found_error
end
end
This is the licencias model definition:
class Licencia < ApplicationRecord
belongs_to :member
validate :date_ordinality
validates_with Validators::LapseValidator
default_scope { order('inicio ASC') }
def date_ordinality
errors.add(:final, ": La fecha de inicio del período de Licencia no puede ser posterior a la fecha de término del período. Verifique por favor.") unless inicio < final
end
end
This is the licencias schema:
create_table "licencias", force: :cascade do |t|
t.date "inicio"
t.date "final"
t.integer "secuencia"
t.integer "member_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["member_id"], name: "index_licencias_on_member_id"
end
This is the app/views/licencias/new.html.erb
<h2>Período de Licencia</h2>
<% flash.each do |message_type, message| %>
<div class="alert alert-<%= message_type %>"><%= message %></div>
<% end %>
<h3>Agregar Licencias de Notario: <%= @member.nombre%></h3>
<div class="container">
<%= render 'form', member: @member %>
</div>
<%= debug(flash) if Rails.env.development? %>
This is the form partial
<%= form_for(@licencia) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<% flash.each do |message_type, message| %>
<div class="alert alert-<%= message_type %>"><%= message %></div>
<% end %>
<div class="col-sm-5">
</div>
<div class="col-sm-2">
<hr>
<%= f.label :inicio, "Fecha de Inicio", class: "form-control-label" %>
<%= f.date_field :inicio, class: "form-control form-fecha" %>
<%= f.label :final, "Fecha de término", class: "form-control-label" %>
<%= f.date_field :final, class: "form-control form-fecha" %>
<%= f.hidden_field :member_id, :value => params[:member_id] %>
<div class="actions">
<%= f.submit "Guardar", class: "btn btn-default" %>
</div>
</div>
<% end %>
Please excuse me for not using a github gist for all the code. Thanks in advance