Why my validation does not pass - ruby-on-rails

I am developing Rails 3 app.
I would like to validate the "Cake" model's "size" attribute input field to only allow user to input +1,-1,+10,-10 and +25,-25, nothing else.
I use the following validation to validate "size":
class Cake < ActiveRecord::Base
validates_format_of :size, :with => /^[-+]?(1|10|25)$/, :message=>'size not allowed.'
...
end
(The "size" attribute in my database "cakes" table is a "double" type.)
In the UI, I always get fail message of the validation even I input 1 or 10 or 25 or +1 or whatever. Why my validation does not pass even the value is right?

I'm not sure if validating an Integer with a Regex works.
You could try validates_inclusion_of :size, :in=>[-1,+1,-10,+10,-25,+25], :message=>'size not allowed.'

Related

Rails validates acceptance not validating

I would like to simply validate a terms checkbox on my form. I have implemented the folowing:
http://guides.rubyonrails.org/active_record_validations.html#acceptance
class User < ActiveRecord::Base
validates :terms, acceptance: true
end
I have stripped the form back to the checkbox only for debugging purposes.
Regardless of the entry passed the :terms does not validate. The form parameters appear to being passed correctly.
Parameters: {"utf8"=>"✓", "authenticity_token"=>"+1dzwEMajQN4cL7KdGjlIw2kFSyVk/36eAhNhdydUXhLfzyT7LnCiUGdfzYt3hD/dD7evIVMiVWePv+7p+scyA==", "user"=>{"terms"=>"1"}, "commit"=>"Register"}
When I update the validation to the following I receive an error stating "Terms must be accepted" regardless of the terms value submitted. This leads me to believe the value from the form is not being passed to the validation.
validates :terms, acceptance: true, :allow_nil => false
OK...
The problem was that the validation helper validates the contents of the row within the table before saving. For this to trigger I needed to assign the ":terms" value to the model for validation.
I was only passing the params hash with the "terms" item within it expecting that to be validated.

Enum validation in Rails 4.2 doesn't work

My User model looks similar to this:
class User < ActiveRecord::Base
enum type: [:admin, :reviewer, :super_admin ]
validates :type, presence: true
validates :type, inclusion: { in: User.types.keys }
end
When I submit anything outside the enum values, the validation doesn't stop the code from running, and I get a 500 error as a response with the following error:
'something submitted' is not a valid type
If I submit a blank field, the validation works:
"type": [
"can't be blank",
"is not included in the list"
]
What am I doing wrong? My code looks identical to this answer
Rails enum doesn't have in-built validation.
The current focus of AR enums is to map a set of states (labels) to an
integer for performance reasons. Currently assigning a wrong state is
considered an application level error and not a user input error.
That's why you get an ArgumentError.
You still can set nil or an empty string to the enum attribute without raising an error.

Rails conditional validation in model

I have a Rails 3.2.18 app where I'm trying to do some conditional validation on a model.
In the call model there are two fields :location_id (which is an association to a list of pre-defined locations) and :location_other (which is a text field where someone could type in a string or in this case an address).
What I want to be able to do is use validations when creating a call to where either the :location_id or :location_other is validated to be present.
I've read through the Rails validations guide and am a little confused. Was hoping someone could shed some light on how to do this easily with a conditional.
I believe this is what you're looking for:
class Call < ActiveRecord::Base
validate :location_id_or_other
def location_id_or_other
if location_id.blank? && location_other.blank?
errors.add(:location_other, 'needs to be present if location_id is not present')
end
end
end
location_id_or_other is a custom validation method that checks if location_id and location_other are blank. If they both are, then it adds a validation error. If the presence of location_id and location_other is an exclusive or, i.e. only one of the two can be present, not either, and not both, then you can make the following change to the if block in the method.
if location_id.blank? == location_other.blank?
errors.add(:location_other, "must be present if location_id isn't, but can't be present if location_id is")
end
Alternate Solution
class Call < ActiveRecord::Base
validates :location_id, presence: true, unless: :location_other
validates :location_other, presence: true, unless: :location_id
end
This solution (only) works if the presence of location_id and location_other is an exclusive or.
Check out the Rails Validation Guide for more information.

How to do a simple regex validation in rails

How can perform a reguler expression to validate for either - or _ in the person username. i dont want to accept any other character like .#()$etc just - or _ so the person can either have a name like mike, mikel_mark or mike-mark. very simple. Thank you
example:
validate_format_of :username, with: "...."
The Rails 3 way to do validations is the following:
validates :username, :format => {:with => /\A[0-9a-z_]+\Z/i}
The form of validate_format_of is more Rails < 3 like and followed the "type of validation" concept, whereas the validates form is attribute based (you write all validations that apply to the attribute in one statement).
Check out the docs here: http://apidock.com/rails/v3.2.13/ActiveModel/Validations/ClassMethods/validates

Validation of fields from some box on the view - Rails

I have an User model. It has next fields:
attr_accessible :user_name, :first_name, :last_name, :email ....
There is a profile view for the User with 6 blocks. Each of them associated with the various fields. Box 1 - first_name and last_name, Box 2 - user_name and email, etc.
I need to validate all the fields (presence, format, etc). But validators must trigger only for those fields, that has came from a particular block (Box 1 or Box 2, for example).
If I write something like next:
validates :user_name, :presence => true
and I will not edit the block with the *user_name*, I will see the error "user Name can't be blank". I can't use *:allow_blank => true* or nil because it can't(!) be blank!
In two words: I must validate only those fields, that was past from the resquest.
What I can do to solve my problem? Thx
You can add if or unless option to skip of particular condition.
validates :user_name, :presence => true, :if => "first_name.blank? and last_name.blank?"
You can pull the specific fields out of your model and create a model for each block, then you add one_to_one relationships to your User model.

Resources