Skip to content

Instantly share code, notes, and snippets.

@lustremedia
Last active August 29, 2015 14:01
Show Gist options
  • Save lustremedia/0497670119305df5b2c3 to your computer and use it in GitHub Desktop.
Save lustremedia/0497670119305df5b2c3 to your computer and use it in GitHub Desktop.
render/redirect_to with flash messages and validation errors in rails 4
<div>
<%= form_for(@entrant, url: contact_path) do |f| %>
<% if !flash.empty? %>
<div id="flash">
<% flash.keys.each do |k| %>
<div class="<%= k %>">
<%= flash[k] %>
</div>
<% end %>
</div>
<% end %>
<% if @entrant.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@entrant.errors.count, "error") %> prohibited this entrant from being saved:</h2>
<ul>
<% @entrant.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br>
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
</div>
class Entrant < ActiveRecord::Base
validates :email, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }
has_many :events, :through => :event_maps
has_many :event_maps, :foreign_key => "entrant_id"
accepts_nested_attributes_for :events, :reject_if => :all_blank
end
class PagesController < ApplicationController
def contact
if request.post? #POST
logger.info("I am a POST")
@entrant=Entrant.new(entrant_params)
@event = Event.find(1)
respond_to do |format|
if @entrant.save
@event.entrants << @entrant
format.html { redirect_to :back, notice: 'Entrant was successfully created and registered.' }
logger.info("I am saved")
format.js
else
logger.info("I am invalid")
#DOES NOT WORK FLASH NEEDS TO BE SET FIRST
#format.html { render action: 'contact', notice: 'Entrant was successfully created and registered.' }
#THIS IS HOW IT IS DONE
format.html { flashme("I am invalid", 'contact') } #CALLING FLASHME FUNCTION
format.js
end
end
else #GET
logger.info("I am a GET")
@entrant=Entrant.new
end
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def entrant_params
params.require(:entrant).permit(:name, :email)
end
# THIS SETS A FLASH MESSAGE BEFORE THE RENDER
# ERRORS ARE ALSO SEND TO THE VIEW SINCE WE'RE REFRESHING
def flashme(msg, action)
# FLASH MUST BE SET !BEFORE! RENDER ACTION
flash[:error] = msg
render action: action
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment