I am trying confirmation validation in Rails4 but it does not work correctly.
When i submit the form the message is "Email confirmation can't be blank" instead of "Email doesn't match confirmation"
Here is my code:
enter code here
#model user.rb
class User < ActiveRecord::Base
validates :email, confirmation: true
validates :email_confirmation, presence: true
end
#view
<div class="field">
<%= f.label :email_confirmation %><br>
<%= f.text_field :email_confirmation %>
</div>
#controller
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: #user }
else
format.html { render :new }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
You can create a custom validation to check if two fields are the same
validate :check_email
def check_email
errors.add(:email_comfirmation, "Test message") if email == email_confirmation
end
Related
Im trying to upload a photo through my Rails app and everything is fine until I click on "update...". Then it throws me an "ActionController::UnknownFormat" error and fails. Here you can find the form I'm using, the update controller and the model I'm referring to.
Form:
<%= form_with(model: current_user, local: true, html: {multipart: true}) do |form| %>
<div class="field">
<%= form.label :profile_pic %>
<%= form.file_field :profile_pic, id: :profile_pic %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
Update method:
def update
#user = current_user
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: #user }
else
render action: :edit
end
end
end
Error seems to be here:
respond_to do |format|
model:
require 'digest'
class User < ApplicationRecord
mount_uploader :profile_pic, ProfilePicUploader
attr_accessor :password
before_save :encrypt_new_password
after_create :build_profile
has_one :profile
has_many :trips
has_many :comments, through: :trips, source: :comments
has_many :posts, through: :trips, source: :posts
scope :recent_comments, ->{where("comments.created_at > ? AND user_id = ?", [6.months.ago, self.id]).limit(3)}
#friends
has_many :users
validates :email, uniqueness: {case_sensitive: false, message: 'El correo debe ser único'}, length: {in: 6..50, too_short: "debe tener al menos %{count} caracteres"}, format: {multiline: true,with: /^.+#.+$/, message: "formato de correo no valido"}
validates :password, confirmation: true, length: {within: 4..20}, presence: {if: :password_required?}
validates :password_confirmation, presence: true
def self.authenticate(email,password)
user = find_by_email(email)
return user if user && user.authenticated?(password)
end
def authenticated?(password)
self.hashed_password == encrypt(password)
end
protected
def encrypt_new_password
return if password.blank?
self.hashed_password = encrypt(password)
end
def password_required?
hashed_password.blank? || password.present?
end
def encrypt(string)
Digest::SHA1.hexdigest(string)
end
def build_profile
Profile.create(user: self, name: self.name, bio:"Im using Tripper!")
end
end
If anyone could tell me please what did I do wrong...
You have used the respond_to block, but you didn't specify the format in which edit action should be rendered.
Try updating the update action as below:
def update
#user = current_user
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: #user }
else
format.html { render 'edit'} # Specify the format in which you are rendering the 'edit' page
format.json { render json: #user.errors } # If required, specify a json format as well
end
end
end
Try to the following by updating the update action
def update
#user = current_user
respond_to do |format|
if #user.update(user_params)
flash[:notice] = 'User was successfully updated.'
format.html {redirect_to user_path(#user) }
format.json { render :show, status: :ok, location: #user }
else
render action: :edit
end
end
end
Hope to help
I ran into a very strange bug in my Rails app: Whenever I try to submit a form I get the error No route matches [PATCH] "/business_cases" (in this case). But after clicking the "Back"-Button in my Browser and filling out + submitting again, it works fine. As this error appears not only in this specific model but almost every other I'm quite lost.. Here is the example.
routes:
business_cases GET /business_cases(.:format) business_cases#index
POST /business_cases(.:format) business_cases#create
new_business_case GET /business_cases/new(.:format) business_cases#new
edit_business_case GET /business_cases/:id/edit(.:format) business_cases#edit
business_case GET /business_cases/:id(.:format) business_cases#show
PATCH /business_cases/:id(.:format) business_cases#update
PUT /business_cases/:id(.:format) business_cases#update
DELETE /business_cases/:id(.:format) business_cases#destroy
routes.rb:
root 'dashboards#index'
get "index" => "pages#index"
resources :users, :orders, :sales, :business_cases
controller (FYI: I use cancancan):
class BusinessCasesController < ApplicationController
load_and_authorize_resource
before_action :authenticate_user!
def index
end
def show
end
def new
end
def edit
end
def create
respond_to do |format|
if #business_case.save
format.html { redirect_to business_cases_url, notice: 'Business case was successfully created.' }
format.json { render :show, status: :created, location: #business_case }
else
format.html { render :new }
format.json { render json: #business_case.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #business_case.update(business_case_params)
format.html { redirect_to business_cases_url, notice: 'Business case was successfully updated.' }
format.json { render :show, status: :ok, location: #business_case }
else
format.html { render :edit }
format.json { render json: #business_case.errors, status: :unprocessable_entity }
end
end
end
def destroy
#business_case.destroy
respond_to do |format|
format.html { redirect_to business_cases_url, notice: 'Business case was successfully destroyed.' }
format.json { head :no_content }
end
end
model:
class BusinessCase < ActiveRecord::Base
validates :name, :description, :presence => true
end
form (shorten):
<%= form_for #business_case, html: { multipart: true } do |f| %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: "form-control", placeholder: "X-Sell" %>
</div>
<% end %>
For some reason my validations aren't working correctly. I can submit the form if it's blank, and it gets processed by the controller. Isn't the point of the model to validate the params before it goes to the controller?
My Controller is:
class SubscribersController < ApplicationController
before_action :set_subscriber, only: [:show, :edit, :update]
# GET /subscribers
# GET /subscribers.json
def index
#subscribers = Subscriber.all
end
# GET /subscribers/1
# GET /subscribers/1.json
def show
# This is Wrong, but You Get The Idea
#subscriber = Subscriber.find_by(params[:id])
end
# GET /subscribers/new
def new
#subscriber = Subscriber.new
end
# GET /subscribers/1/edit
def edit
end
# POST /subscribers
# POST /subscribers.json
def create
#subscriber = Subscriber.new(subscriber_params)
respond_to do |format|
if #subscriber.save
format.html { redirect_to :back, notice: 'Thanks For Joining Our Mailing List!' }
format.json { render :back, status: :created, location: #subscriber }
else
format.html { redirect_to :back, notice: 'Error, Invalid Entry, or you are on the List Already!'}
format.json { redirect_to :back, #subscriber.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /subscribers/1
# PATCH/PUT /subscribers/1.json
def update
respond_to do |format|
if #subscriber.update(subscriber_params)
format.html { redirect_to :back, notice: 'Subscriber was successfully updated.' }
format.json { redirect_to :back, status: :ok }
else
format.html { redirect_to :back }
format.json { render json: #subscriber.errors, status: :unprocessable_entity }
end
end
end
# DELETE /subscribers/1
# DELETE /subscribers/1.json
def destroy
if #subscriber = Subscriber.find_by(params[:email])
respond_to do |format|
if #subscriber.destroy
format.html { redirect_to :back, notice: 'Subscriber was successfully destroyed.' }
format.json { head :no_content }
else
format.html { redirect_to :back, notice: 'Something Wrong' }
format.json { render json: #subscriber.errors, status: :unprocessable_entity }
end
end
else
redirect_to :back
flash[:error] = "Couldn't Find That Email Database!"
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_subscriber
#subscriber = Subscriber.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def subscriber_params
params.require(:subscriber).permit(:name, :email)
end
end
and my model is:
class Subscriber < ActiveRecord::Base
before_validation :downcase_email
validates_uniqueness_of :email
validates_format_of :email,:with => Devise::email_regexp
validates_presence_of :name, :message => "Name can't be blank"
validates_presence_of :email, :message => "Need an Email!!", on: :destroy
private
def downcase_email
self.email = self.email.downcase if self.email.present?
end
end
lastly my form:
<div class="five wide column subscriber">
<div class="ui inverted form segment">
<%= simple_form_for(#subscriber) do |f| %>
<%= f.error_notification %>
<h3 class="ui header">Join Our Mailing List</h3>
<div class="two fields">
<div class="field">
<%= f.input :name, placeholder: "Enter Name", required: true, error_html: { id: 'password_error'}%>
</div>
<div class="field">
<%= f.input :email, placeholder: "Enter Email", type: "email", required: true%>
</div>
</div>
<%= f.submit "Join", class: "ui blue submit button" %>
<% end %>
</div>
</div>
Let me know if I need to supply any more information. I hope this is an easy fix, but I'm not sure what I'm doing wrong.
I have an issue with a form since after entering the data, I get Couldn't find Employeur without an ID when my show method is called. I think it is due to my nested resources.
Here are my routes:
resources :users do
resource: employeur
resource: prestataire
end
My user controller, that sends me right to the employeur form once the user one has been filled:
class UsersController < ApplicationController
#TODO index user doit être suprimé quand inutile pour dev
def index
#users = User.all
end
def show
#user = User.find(params[:id])
end
def new
#user = User.new
end
# GET /users/1/edit
def edit
#user = User.find(params[:id])
end
# POST /users
# POST /users.json
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
if params[:commit] == 'Prestataire'
format.html { redirect_to new_user_prestataire_path(user_id: #user), notice: "Renseignez vos informations d'employeur" }
format.json { render action: 'show', status: :created, location: #user }
else
format.html { redirect_to new_user_employeur_path(user_id: #user), notice: "Renseignez vos informations de prestataire" }
format.json { render action: 'show', status: :created, location: #user }
end
else
format.html { render action: 'new' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
#user = User.find(params[:id])
respond_to do |format|
if #user.update(user_params)
if params[:commit] == 'Prestataire'
format.html { redirect_to new_user_prestataire_path(user_id: #user), notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { redirect_to new_user_employeur_path(user_id: #user), notice: "User was successfully updated." }
format.json { head :no_content }
end
else
format.html { render action: 'edit' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
#user = User.find(params[:id])
#user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :surname, :forename, :civility, :phone)
end
end
My employeur form with which I'm in trouble:
<%= form_for [#user, #employeur] do |f| %>
<% if #employeur.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#employeur.errors.count, "error") %> prohibited this employeur from being saved:</h2>
<ul>
<% #employeur.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :siren, 'Siren: ' %><br>
<%= f.text_field :siren %>
</div>
<div class="field">
<%= f.label :societe, 'Société: ' %><br>
<%= f.text_field :societe %>
</div>
<div class="field">
<%= f.label :code_postal, 'Code Postal: ' %><br>
<%= f.text_field :code_postal %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And my employeur controller which can't find my employeur params:
class EmployeursController < ApplicationController
before_filter :load_user
def index
#employeurs = #user.employeur.all
end
def show
#employeur = Employeur.find(params[:id])
end
def new
#employeur = #user.build_employeur
end
def edit
#employeur = Employeur.find(params[:id])
end
def create
#employeur = #user.build_employeur(employeur_params)
respond_to do |format|
if #employeur.save
format.html { redirect_to [#user, #employeur], notice: 'Employeur was successfully created.' }
format.json { render action: 'show', status: :created, location: #employeur }
else
format.html { render action: 'new' }
format.json { render json: #employeur.errors, status: :unprocessable_entity }
end
end
end
def update
#employeur = Employeur.find(params[:id])
respond_to do |format|
if #employeur.update_attributes(employeur_params)
format.html { redirect_to [#user, #employeur], notice: 'Employeur was successfully created.' }
format.json { render action: 'show', status: :created, location: #employeur }
else
format.html { render action: 'new' }
format.json { render json: #employeur.errors, status: :unprocessable_entity }
end
end
end
def destroy
#employeur = Employeur.find(params[:id])
#employeur.destroy
respond_to do |format|
format.html { redirect_to #user }
format.json { head :no_content }
end
end
private
def load_user
#user = User.find(params[:user_id])
end
def employeur_params
params.require(:employeur).permit(:siren, :societe, :code_postal)
end
end
I've decided to edit my first post to add all my routes linked to employeurs that #Sirius ROR:
user_employeur POST /users/:user_id/employeur(.:format) em
ployeurs#create
new_user_employeur GET /users/:user_id/employeur/new(.:format) em
ployeurs#new
edit_user_employeur GET /users/:user_id/employeur/edit(.:format) em
ployeurs#edit
GET /users/:user_id/employeur(.:format) em
ployeurs#show
PATCH /users/:user_id/employeur(.:format) em
ployeurs#update
PUT /users/:user_id/employeur(.:format) em
ployeurs#update
DELETE /users/:user_id/employeur(.:format) em
ployeurs#destroy
I've also made a significant change:
Became:
Because I've made a signifant change on my Employeur Model:
class Employeur < ActiveRecord::Base
model_name.instance_variable_set :#route_key, 'employeur'
belongs_to :user
has_many :projets, as: :projetable
has_many :prestataires, through: :projets
has_many :offres, through: :projets
has_many :feedbacks, through: :projets
validates :siren, :societe, :code_postal, presence: true
end
According to what I've eventually found on internet, the first line deals with the url issue. Despite this change, I still get the exact same error: Couldn't find Employeur without an ID.
Here is also my User Model:
class User < ActiveRecord::Base
has_one :prestataire
has_one :employeur
accepts_nested_attributes_for :employeur, allow_destroy: true
has_secure_password
end
Try removing url option from form_for as form for automatically builds the post url
<%= form_for [#user, #employeur] do |f| %>
This must work well.
I have a text_field that I want set 3 validation on this. In this text_field I get reporter's phone number. Each reporter has_one reporterprofile. I want when reporter enter his phone_number, I check validates_numericality_of and validates_length_of and if these two are true, then check uniqueness validation, If this phone_number is new, thats ok, I create a reporterprofile and redirect_to reporterprofile by this new id, But if this phone_number is exist, I want page is redirect_to this reporterprofile without created new reporter.
reporter.rb
class Reporter < ActiveRecord::Base
has_one :reporterprofile
before_create :build_reporterprofile
validates :phone_number, uniqueness: true
validates_numericality_of :phone_number
validates_length_of :phone_number, :minimum => 11, :maximum => 11
end
reporters_controller.rb
def create
#reporter = Reporter.new(reporter_params)
respond_to do |format|
if #reporter.save
format.html { redirect_to edit_reporterprofile_path(:id => #reporter.reporterprofile), notice: 'Reporter was successfully created.' }
format.json { render action: 'show', status: :created, location: #reporter }
else
if
format.html { render action: 'new' }
format.json { render json: #reporter.errors, status: :unprocessable_entity }
end
end
end
end
I can redirect_to edit_reporterprofile_path when reporter doesn't save, but if I do this, numerically and length validations are don't check. How can I redirect reporter that is exist to his profile?
First, check if a Reporter with the given phone number exists. If so, redirect to the reporterprofile path. Otherwise, create the new reporter. There are various ways to organize the logic to handle this. Here it is all shoved into the "create" action of the reporters controller.
def create
existing_reporter = Reporter.includes(:reporterprofile).find_by(phone_number: reporter_params[:phone_number])
if existing_reporter
redirect_to reporterprofile_path(existing_reporter.reporterprofile)
else
#reporter = Reporter.new(reporter_params)
respond_to do |format|
if #reporter.save
format.html { redirect_to edit_reporterprofile_path(:id => #reporter.reporterprofile), notice: 'Reporter was successfully created.' }
format.json { render action: 'show', status: :created, location: #reporter }
else
if
format.html { render action: 'new' }
format.json { render json: #reporter.errors, status: :unprocessable_entity }
end
end
end
end
end
I'd start by populating the validates method with more than what you've got now. This will remove the dependency on the other two methods you have, which should go to fixing some of the issue:
validates :phone_number,
length: { is: 6 },
numericality: true,
uniqueness: true