rails validations error messages not working - ruby-on-rails

I am trying to make a login in and sign up page but when i try to validate the email and password no error messages pop up I though they are supposed to pop up the the condition isn't met.
i have tried error messages through layouts view and helper but none work or are too confusing for me to understand.
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.create(password: params[:password], email: params[:email], firstname: params[:firstname], lastname: params[:lastname])
if #user.save
redirect_to user_path(#user)
else
redirect_to root_path
end
end
def show
#user = User.find(params[:id])
end
end
This is my users controller
This is my user model
class User < ApplicationRecord
has_secure_password
validates :email, presence: true, uniqueness: true
validates :password, length: { minimum: 4 }
validates_format_of :email, :with => /\A([^#\s]+)#((?:[-a-z0-9]+\.)+
[a-z]{2,})\Z/i, :message => "hollksd"(just for testing)
end
This is my new user view
<%= form_for #user do |form| %>
<p> First name:<%= form.text_field :firstname %></p>
<p>Last name:<%= form.text_field :lastname %></p>
<p>Email:<%= form.email_field :email %></p>
<p>Create password:<%= form.password_field :password %></p>
<%= form.submit %>
<%end%>
if anyone could help it would be appreciated!

It seems like your html elements are not associated to User model please try to use form_for tag instead somewhat like below
<%= form_for #user do |form| %>
<%= form.text_field :first_name %>
<%= form.text_field :last_name %>
<%= form.submit %>
<%end%>
Also please use render :new instead of redirect_to root_path

You you need to update your create action to something like this:
def create
#user = User.new(password: params[:password], email: params[:email], firstname: params[:firstname], lastname: params[:lastname])
if #user.save
redirect_to user_path(#user)
else
render :new
end
end
Why render new when it fail to save? Because we need to let know know that this form is not valid, and by rendering new with the #user object, you get access to #user.errors where you can do whatever you like (formally form will render a red border and error message next to input).

Related

How do I make error notices in this ruby form?

How can I make an error notice when somebody leaves spaces empty, etc...
I tried enumerous codes and they either didn't work or failed... I even installed a gem but nothing worked until now... please help with ideas/solutions
<div class="jumbotron"
<div class="container">
<h2>Signup</h2>
<%= form_for :user, url: '/users' do |f| %>
Número de Empregado: <br>
<%= f.number_field :NumeroEmpregado %><br>
Primeiro e Último Nome: <br>
<%= f.text_field :nome %><br>
Password: <br>
<%= f.password_field :password %><br>
Confirmação Password: <br>
<%= f.password_field :password_confirmation %><br>
<%= f.submit "Submit" %>
</div>
</div>
<% end %>
Controller:
class UsersController < ApplicationController
def new
end
def create
user = User.new(user_params)
if user.save
session[:user_id] = user.id
redirect_to '/'
else
flash[:error] = 'invalid value'
end
end
private
def user_params
params.require(:user).permit(:NumeroEmpregado, :nome, :password, :password_confirmation)
end
end
Rails only can validate when you submitted your form. In this case, you can check out this guide.
In other case, if you want immediately show validate message when user enter into input, you must validate it by using Javascript. You also can use Jquery validation plugin to do that.
Hope its help :)
you should use jquery validations if you want to check if the field is empty type validations before submit https://jqueryvalidation.org/documentation/ follow this link.
Or if you are ok with validating fields on submit then in create or update action of your controller you can check from the params if that field is empty. then you can show flash messages like this
flash[:notice] = 'valid value'
flash[:error] = 'invalid value'
Or you can add model level validations on that fields http://guides.rubyonrails.org/active_record_validations.html here
You can use the Active Record Validations.
If you have a model called User, then you can specify which attributes to validate for presence using the validates method and setting the presence to true, this will check if the field on the form has been filled, also if has only whitespaces.
For instance:
class User < ApplicationRecord
validates :nome, presence: true
...
For your controller:
def create
user = User.new(user_params)
if user.save
session[:user_id] = user.id
redirect_to '/'
else
flash[:error] = 'invalid value'
redirect_to new_user_path
end
end
Redirect to the new user path with flash[:error] as "invalid value".
For your view:
<% if flash[:error] %>
<div class="error">
<%= flash[:error] %>
</div>
<% end %>

Nested model in Rails3

I have two models user and profile.
I want to save the username and password in user and other user profile details in profile.
Now,
The user model has:
has_one :profile
accepts_nested_attributes_for :profile
attr_accessible :email, :password
The profile model has
belongs_to :user
attr_accessible :bio, :birthday, :color
The user controller has
def new
#user = User.new
#profile = #user.build_profile
end
def create
#user = User.new(params[:user])
#profile = #user.create_profile(params[:profile])
if #user.save
redirect_to root_url, :notice => "user created successfully!"
else
render "new"
end
end
The view new.html.erb have fields for both user and profile.
However,when I run this web application it shows error:
Can't mass-assign protected attributes: profile
on debug it stuck at #user = User.new(params[:user]) in create action
so,what is wrong? I have also tried putting :profile_attributes in attr_accessible but it doesn't help!please help me to find out solution.
First off, as suggested by #nash, you should remove #profile = #user.create_profile(params[:profile]) from your create action. accepts_nested_attributes_for will automatically create your profile for you.
Check that your view is set up correctly for nested attributes. Should shouldn't be seeing anything in params[:profile]. The profile attributes need to come through in params[:user][:profile_attributes] for nested models to work correctly.
In summary, your create action should look like this:
def create
#user = User.new(params[:user])
if #user.save
redirect_to root_url, :notice => "user created successfully!"
else
render "new"
end
end
Your form view (typically _form.html.erb) should look something like this:
<%= form_for #user do |f| %>
Email: <%= f.text_field :email %>
Password: <%= f.password_field :password %>
<%= f.fields_for :profile do |profile_fields| %>
Bio: <%= profile_fields.text_field :bio %>
Birthday: <%= profile_fields.date_select :birthday %>
Color: <%= profile_fields.text_field :color %>
<% end %>
<%= f.submit "Save" %>
<% end %>
For more information, see this old but great tutorial by Ryan Daigle.

Why isn't my rails controller/form persisting any data to my local database?

I'm new to Ruby on Rails, and as my first project I'm creating a beta sign-up page for my startup. I just want to save the users email address to a database for future use, and I am not able to persist any data into my database. I can add emails through the rails console, but my form/controller are not working. What's wrong?
User Model:
class User < ActiveRecord::Base
attr_accessible :email
before_save { |user| user.email = email.downcase }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness:
{case_sensitive: false }
end
User Controller:
class UsersController < ApplicationController
def index
end
def create
User.create params[:email]
redirect_to :back, :notice => "Success!"
end
end
Home page HTML:
<h1>######</h1>
<p>Welcome to #####! Give us your email address, and we'll keep you informed on our
latest happenings.
You'll also be placed on the list for our private alpha and beta testings.</p>
<%= render 'form' %>
Form Partial:
<%= form_for User.new do |f| %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.submit %>
<% end %>
Thanks!
First, create the user with params[:user] not params[:email]. If you want just the email address, put params[:user][:email].
This is because params is a nested hash and looks like this:
params[:user] = { email: "name#example.com" }.
Second, use conditional logic in case the email address does not pass validation and doesn't save.
#user = User.new(params[:user])
if #user.save
redirect_to :back, :notice => "Success!"
else
# display error messages
end
or if you want to get verbose:
#user = User.new(:email => params[:user][:email])
This is wrong:
User.create params[:email]
It should be:
User.create params[:user]

Pass model between controllers and views in Ruby on Rails

I have signup form on my home screen. If user inputs invalid data I redirect him to /signin page. On this page I can see filled fields, but errors descriptions are empty.
Here is my UsersController:
class UsersController < ApplicationController
def new
#user = User.new(params[:user])
end
def create
#user = User.new(params[:user])
print #user
if #user.save
else
render 'new'
end
end
end
Method I use to show errors
module ApplicationHelper
def errors_for(model, attribute)
if model.errors[attribute].present?
content_tag :div, :class => 'well error' do
content_tag :ul do
model.errors[attribute].collect {|item| concat(content_tag(:li, item))}
end
end
end
end
end
My form partial:
<%= f.label :user_name %>
<%= f.text_field :user_name, :class=>"input-medium" %>
<%= errors_for(#user, :user_name) %>
<%= f.label :email %>
<%= f.text_field :email, :class=>"input-medium " %>
<%= errors_for(#user, :email) %>
<%= f.label :password %>
<%= f.password_field :password, :class=>"input-medium" %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation, :class=>"input-medium" %>
and my signup view:
<section class="centered user-form-container">
<div class="user-form well pull-left">
<div class="centered">
<h1>Sign up</h1>
<%= form_for(#user, :action=>"create") do |f| %>
<%= render 'signup', :f=>f %>
<%= f.submit "Sign up" %>
<% end %>
</div>
</div>
</section>
In this situation, I believe you need to use flash.now, something like this:
Per the rails docs:
By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create action fails to save a resource and you render the new template directly, that’s not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use flash.now in the same way you use the normal flash:
def create
#user = User.new(params[:user])
print #user
if #user.save
else
# start with this, then expand the error text
flash.now[:error] = "Could not save user"
render 'new'
end
end
You would do this in your validation method.
If you are using a standard rails validation you would do this:
validates_presence_of :foo, :message => 'Message you want to display here'
If you are doing a custom validation then this:
def my_validation_method
begin
my_validation_code_here
rescue
self.errors[:base] << 'Message you want to display here'
end
end
def new
#user = User.new(params[:user])
if (!params[:user].nil?)
#user.valid?
end
end

Why is my rails simple validation not working

I have a very basic rails app. I am playing around with validation.
Controller
class PagesController < ApplicationController
def new
#user = User.new
end
def edit
#user = User.new(:state => params[:state], :country => params[:country])
#user.save
end
end
Model
class User < ActiveRecord::Base
validates_presence_of :country
validates_presence_of :state
end
Views/pages/edit.html.erb
<% form_for :user, #user, :url => { :action => "edit" } do |f| %>
<%= f.text_field :country %>
<%= f.text_field :state %>
<%= submit_tag 'Create' %>
<% end %>
All I want to do is click Create when I have not entered anything and then have a validation come up and list the required fields. I've read some tutorials and they make it so simple. Why can't I get this to work? what am i doing wrong? When i create a scaffold then it works ok but that generates a scaffold.css in public/stylesheets. W/out scaffold right now i have no stylesheet in the public folder.
you're sending the form to the "edit" action, which doesn't do any processing. You need it to go to the "create" action, which should look something like this:
def create
#user = User.new(params[:user])
if #user.save
flash[:notice] = 'Your user was successfully created.'
redirect_to users_path
else
render :action => 'edit'
end
end
Your form_for line can be short and sweet. Also, you need to call error_messages to get the auto-generated list of errors:
<% form_for #user do |f| %>
<%= f.error_messages %>
...other fields go here...
<% end %>
See Rails conditional validation: if: doesn't working
It seems like you think validates ... if: works differently as it actually does. This line
validates :to_id, presence: true, if: :from_different_to?
translates to validate that the to_id is present if the from_different_to method returns true. When from_different_to evaluates to false then do not validate.

Resources