Can I use validation parameters in controller? - ruby-on-rails

In controller action I have two parameters: params[:name] and params[:email]. I would like check them. if they not null and haven't some wrong symbols. Why I asking - because I am not sure can I use validation in controller and I don't know how check param for some symbols...use regular function?...Here is my try:
Controller:
validates :name, :presence => true
validates :email, :presence => true
def check
name = params[:name].valid?
email = params[:email].valid?
end

The validation should occur in the model. Remember the controller should only translate HTTP requests into your application actions.
When you are creating an object you are doing it at the Model layer, so the validation should be at this layer, the model.

Related

How do I validate certain fields with rails devise on registration only

I have a set of custom fields attached to a devise model called Entrant.
I have two forms, one for registration form (three fields) and one which sits in the account area (12 fields). Most of the custom fields area required but only within the form the sits in the account area.
How do I achieve this?
I am using rails 4.2 and ruby 2.1
You can simply specify validations on actions, that is:
validates :name, presence: true, on: :create # which won't validate presence of name on update action
If you ask where to put your custom fields, then generate devise's views and update corresponding ones with these fields.
There are several ways! You could do conditional validations, for instance
class Entrant < ActiveRecord::Base
validate :foo, if: :account_area?
def account_area?
!new_record? # Assumes that Entrant that has already been saved
# is in the account area
end
end
However, it sounds like your needs are advanced enough that you should consider making a Form Object
A form object is an object that accepts parameters, performs validations on that data, then saves a model instance.
class AccountForm
include ActiveModel::Model
include Virtus # Provides AR like attribute functionality and mass assignment
def initialize(entrant)
#entrant = entrant
end
attribute :foo, String
validates :foo, presence: true # This is only used on the account page, so no need to mess with conditional logic
def save
if valid?
persist!
true
else
false
end
end
def persist!
#entrant.update_attributes(foo: self.foo)
end
end
This is just a great example of how non-rails-specific object oriented programming can make your life easier and your app more maintainable. Make a class like above, stick it in app/forms and restart your server. Then in your controller, you'll just pass it the model
class EntrantController < ApplicationController
def update
#form = Form.new(Entrant.find(params[:id]))
#form.attributes = params[:entrant]
if #form.save
redirect_to some_path
else
render "edit"
end
end
end
By default devise only asks for a combination of email/password, you can add other fields by adding a sanitizer (see there -> Devise how to add a addtional field to the create User form?).
If you want to add other fileds to validate, you should create a secondary Entrant controller and add a specific callback to your model.
Typically:
after_update :validate_entrant_form, if: :property_changed?
I hope this will help you.
validates :name, presence: true, if: :condition_holds?
def condition_holds?
# some code here that evaluates to a boolean
end
Maybe this way help you.
Add attribute in devise model : say attr_accessor :validate_certain. In your controller action, devise model instance say #user have to update like this #user.validate_certain = true. and change your appropriate validation conditions in devise model
validates :name, presence: true, if: :validate_certain_changed?
def validate_certain_changed?
validate_certain.present?
end
When I have to do something like this I like to think of it as it validates if something in in the field but you can also take a nil value
Entrant.validates_presence_of(:foo, :allow_nil => true)
I also have this concern when using devise on customer with forms on separate pages updating different set of customer fields
I believe most of the solution works but I was looking for the simplest, easiest and foolproof way to implement the solution
Thus came this.
validates :phone, :country, :postal_code, :street_address, presence: true, allow_nil: true
The allow_nil: true instruct the model to validate the fields ONLY if it exists on the submitted form. If you want more protection, you can use extra para like :on => :update

Only validate if called from a specific controller in rails

I'm trying to make a validation in a model that only is enforced if the model is called from a specific controller.
In my controller I have:
#created_by_user = true
#message.save
In my model I have
validates :subject, length: {in: 0..78, if: #created_by_user}
However it seems that even if I save this model from a different script or controller the validation is still checked. How do I get the results I want?
From the controller where you dont need validation, just call
#message.save(:validate => false)

Custom Validations Rails Model

I have a contact form and would like to show individual messages depending on what has failed.I would like to use flash messages. So from what i have read so far i can create a custom method (or i think it just overrides the one in place?)
So for example, i want to validate the presence of the name field
Class Message
attr_accessor :name
validates :name, :presence => true
def validate
if self.name < 0
errors.add(:name, "Name cannot be blank")
end
end
end
Within my controller i normally use a generic message
flash.now.alert = "Please Ensure all Fields are filled in"
Is there a way to call the particular message that failed validation?
Thanks
There is a plugin available, u can follow the below url
https://github.com/jeremydurham/custom-err-msg
Check the method validates because you can pass a message argument with the desired message.
validates :name, :presence => {:message => 'The name can't be blank.'}

Check if an input box exists in rails

I have to check if confirm_password input box exists in form.If it exists,
I need to do this:
validates :password,:confirmation=>true
else
set confirmation to false.
Detail explanation for the problem:
I'm using rails client_side_validation gem which converts models validation into javascript form validation.
There is a little problem with this as login and sign up belongs to same table both of them have one Model. Now when I'm adding this in model for validation:
validates :password,:confirmation=>true
It will not let me to login as validation will become false as there is no confirm_password input box on login.It will only work on signup.
Assuming a model User add #user.is_signup = true to the signup action in users_controller. In your User model add attribute_accessor :is_signup and validates :confirm_password, :confirmation => true, :if => :is_signup.
In your signup form you could have a hidden field that gets passed in the form. If the attribute is present and returns true then you validate the presence of the password confirmation.
Signup form, somewhere inside the form tags:
<%= form.hidden_field :is_signup, true %>
Model:
attribute_accessor :confirm_password
attribute_accessor :is_signup
validates :confirm_password, :presence => true, :if => :validate_confirm_password?
def validate_confirm_password?
is_signup
end

preventing rails validation based on previous validation

I have a model with 2 validations on the 'name' attribute. It goes something like this:
validates :name, :uniqueness => true
validate do
errors.add(:name, "is dumb") if name_is_dumb?
end
I don't want the 2nd validation to run if the first validation fails (the name is not unique).
What's the best and cleanest way to do this?
According to the documentation:
Callbacks are generally run in the
order they are defined, with the
exception of callbacks defined as
methods on the model, which are called
last.
So the following snippet should work:
validates :name, :uniqueness => true
validate do
errors.add(:name, "is dumb") unless errors[:name].nil?
end

Resources