Validate Param Types in Rails - ruby-on-rails

I've been looking all over the place and I'm wondering if I'm doing something wrong. And just to double check, I'll ask you guys!
So I'm receiving params in a Rails controller. One key, value pair is :status => true/false. However, I find that when I try to post status as a string like
:status => "THIS IS NOT A BOOLEAN"
and create my object in my controller, the :status attribute of my object becomes false.
Therefore, is there any clean way in rails to validate that my :status corresponds to a boolean?
Thanks!

This very strange method will to the trick
def is_boolean?(item)
!!item == item
end
params[:status] = 'some string'
is_boolean?(params[:status])
# => false
params[:status] = true
is_boolean?(params[:status])
# => true
A slightly more intuitive version would be
def is_boolean?(item)
item == false || item == true
end

Validation
The Rails way to do it is to validate in the model (from the docs):
#app/models/model.rb
Class Model < ActiveRecord::Base
validates :status, inclusion: { in: [true, false] }, message: "True / False Required!"
end
--
MVC
The reason for this is twofold:
DRY
MVC
If you want to keep your application DRY, you need to make sure you have only one reference to a validation throughout. Known as the "Single Source Of Truth", it means if you try and populate the model with other controllers / methods, you'll still invoke the same validation
Secondly, you need to consider the MVC (Model-View-Controller) pattern. MVC is a core aspect of Rails, and means you have to use your controller to collate data only - pulling & compiling data in the model. This is also true for validations -- always make sure you keep your validations with the data (IE in the model)

The above #Iceman solution is good if you are only doing it once place but you keep doing/repeating it in other places i suggest you to create to_bool method. i.e
class String
def to_bool
return true if self == true || self =~ (/(true|t|yes|y|1)$/i)
return false if self == false || self.blank? || self =~ (/(false|f|no|n|0)$/i)
raise ArgumentError.new("invalid value for Boolean: \"#{self}\"")
end
end
and put this method in intializer or in library. And, you can simply do this
Mymodel.new(status: params[:status].to_s.to_bool)
we are doing to_s just because to convert nil to '' incase the status key isn't in params .

Related

Rails 4 hstore defining datatypes

So I know that hstore only stores in string either key and especially value. I'm looking for a way to set their datatypes. Is there a way in rails or hstore to do this?
So far what I did was to override the getters and depending on the datatype I want. This is what I have so far:
class ModelWithHstore < ActiveRecord::Base
store_accessor :properties, :some_boolean_field, :some_integer_field, :some_datetime_field
validate :validate_range
def some_boolean_field
return if self[:properties].nil? || self[:properties][__method__.to_s].nil?
if [true, 'true', '1'].include? self[:properties][__method__.to_s]
return true
elsif [false, 'false', '0'].include? self[:properties][__method__.to_s]
return false
end
self[:properties][__method__.to_s]
end
def some_integer_field
return if self[:properties].nil? || self[:properties][__method__.to_s].nil?
self[:properties][__method__.to_s].to_i
end
def some_datetime_field
return if self[:properties].nil? || self[:properties][__method__.to_s].nil?
DateTime.strptime(self[:properties][__method__.to_s].to_s, '%F %T')
end
private
def validate_range
errors.add(:some_integer_field, "value out of range") if !some_integer_field.between?(10, 90)
end
end
And since they are getters. I think they are being used too in validators and some other places. But I really am not sure if something like this already exists or is there a better way to implement this.
Cheers!
You can try hstore_accessor gem

Validation Hash fields using mongoid

I am working on mongoDB with Rails. So using gem mongoid, Anyone know how to validate Hash fields in model?
We have to write custom validation methods
Here explained how we are writing custom validation methods
Looking for a solution, I came to a custom validator that appears good to me and it can be used generically.
private
def fix_content(input_hash, valid_fields)
temphash = {}
input_hash.each do |k,v|
k=k.to_sym
if valid_fields.has_key? k
case valid_fields[k]
when 'integer'
v=v.to_i
when 'boolean'
v=(v=='true' || v==true)
when 'float'
v=v.to_f
when 'array'
v = "#{v.class}"=="Array" ? v : []
else
v=v.to_s
end
temphash[k]=v
end
end
temphash
end
Let's suppose we have this field:
field :fieldname, type: Hash, default: {hfield1: 0, hfield2: [], hfield3: false}
Actually, it's not a validator, it's a callback. It works like this:
before_save :fieldname_fix_content
Under private:
def fieldname_fix_content
# we show the callback what fields will be processed. All others will be disposed of
self.fieldname = fix_content(self.fieldname, {:hfield1=> 'integer', :hfield2=>'array', :hfield3=>'boolean'})
end

Rails model.valid? flushing custom errors and falsely returning true

I am trying to add a custom error to an instance of my User model, but when I call valid? it is wiping the custom errors and returning true.
[99] pry(main)> u.email = "test#test.com"
"test#test.com"
[100] pry(main)> u.status = 1
1
[101] pry(main)> u.valid?
true
[102] pry(main)> u.errors.add(:status, "must be YES or NO")
[
[0] "must be YES or NO"
]
[103] pry(main)> u.errors
#<ActiveModel::Errors:[...]#messages={:status=>["must be YES or NO"]}>
[104] pry(main)> u.valid?
true
[105] pry(main)> u.errors
#<ActiveModel::Errors:[...]#messages={}>
If I use the validate method from within the model, then it works, but this specific validation is being added from within a different method (which requires params to be passed):
User
def do_something_with(arg1, arg2)
errors.add(:field, "etc") if arg1 != arg2
end
Because of the above, user.valid? is returning true even when that error is added to the instance.
In ActiveModel, valid? is defined as following:
def valid?(context = nil)
current_context, self.validation_context = validation_context, context
errors.clear
run_validations!
ensure
self.validation_context = current_context
end
So existing errors are cleared is expected. You have to put all your custom validations into some validate callbacks. Like this:
validate :check_status
def check_status
errors.add(:status, "must be YES or NO") unless ['YES', 'NO'].include?(status)
end
If you want to force your model to show the errors you could do something as dirty as this:
your_object = YourModel.new
your_object.add(:your_field, "your message")
your_object.define_singleton_method(:valid?) { false }
# later on...
your_object.valid?
# => false
your_object.errors
# => {:your_field =>["your message"]}
The define_singleton_method method can override the .valid? behaviour.
This is not a replacement for using the provided validations/framework. However, in some exceptional scenarios, you want to gracefully return an errd model. I would only use this when other alternatives aren't possible. One of the few scenarios I have had to use this approach is inside of a service object creating a model where some portion of the create fails (like resolving a dependent entity). It doesn't make sense for our domain model to be responsible for this type of validation, so we don't store it there (which is why the service object is doing the creation in the first place). However for simplicity of the API design it can be convenient to hang a domain error like 'associated entity foo not found' and return via the normal rails 422/unprocessible entity flow.
class ModelWithErrors
def self.new(*errors)
Module.new do
define_method(:valid?) { false }
define_method(:invalid?) { true }
define_method(:errors) do
errors.each_slice(2).with_object(ActiveModel::Errors.new(self)) do |(name, message), errs|
errs.add(name, message)
end
end
end
end
end
Use as some_instance.extend(ModelWithErrors.new(:name, "is gibberish", :height, "is nonsense")
create new concerns
app/models/concerns/static_error.rb
module StaticError
extend ActiveSupport::Concern
included do
validate :check_static_errors
end
def add_static_error(*args)
#static_errors = [] if #static_errors.nil?
#static_errors << args
true
end
def clear_static_error
#static_errors = nil
end
private
def check_static_errors
#static_errors&.each do |error|
errors.add(*error)
end
end
end
include the model
class Model < ApplicationRecord
include StaticError
end
model = Model.new
model.add_static_error(:base, "STATIC ERROR")
model.valid? #=> false
model.errors.messages #=> {:base=>["STATIC ERROR"]}
A clean way to achieve your needs is contexts, but if you want a quick fix, do:
#in your model
attr_accessor :with_foo_validation
validate :foo_validation, if: :with_foo_validation
def foo_validation
#code
end
#where you need it
your_object.with_foo_validation = true
your_object.valid?

Does Rails have a way to convert checkboxes from "on" to true?

When a controller receives the params of a checked checkbox it comes back as "on" if the box was checked. Now in my case I'm trying to store that value as a boolean, which is typically what you want to with values from checkboxes. My question is, does rails have a way to automatically convert "on" (or even exists) to true/false or do I need to do the following?
value = params[my_checkbox] && params[my_checkbox] == "on" ? true : false
You can just use:
value = !params[:my_checkbox].nil?
as the checkbox would not return any value if not checked (implied by this forum)
The best way of doing this is to create a custom setter for the field in the database, something like this:
class Person < ActiveRecord::Base
def active=(value)
value = value == 'on' ? true : false
super(value)
end
end
That way you don't have to worry about it in the controller and it's the model that knows what value it is supposed to be. When you go to the view rails automatically checks a checkbox from a boolean field. Just in case that didn't work you could also define your own getter.
This can be then used for example in conjunction with store accessor something like this:
class Person < ActiveRecord::Base
validates :active, inclusion: {in: [true, false]}
validates :remember_password, inclusion: {in: [true, false]}
store :settings,
accessors: [:active, :remember_password],
coder: JSON
def active=(value)
value = value == 'on' ? true : false
super(value)
end
def remember_password=(value)
value = value == 'on' ? true : false
super(value)
end
end
Note that the setting field in the database has to be text so you can put more stuff in it.

Why does Model.new in Rails 3 do an implicit conversion?

I'm facing a weird behavior in Rails 3 model instantiation.
So, I have a simple model :
class MyModel < ActiveRecord::Base
validates_format_of :val, :with => /^\d+$/, :message => 'Must be an integer value.'
end
Then a simple controller :
def create
#mod = MyModel.new(params[:my_model])
if #mod.save
...
end
end
first, params[:my_model].inspect returns :
{:val => 'coucou :)'}
But after calling #mod = MyModel.new(params[:my_model]) ...
Now, if I call #mod.val.inspect I will get :
0
Why am I not getting the original string ?
At the end the validates succeed because val is indeed an integer.
Is this because val is defined as an integer in the database ?
How do I avoid this behavior and let the validation do his job ?
If val is defined as an integer in your schema then calling #my_model.val will always return an integer because AR does typecasting. That's not new to rails 3, it's always worked that way. If you want the original string value assigned in the controller, try #my_model.val_before_type_cast. Note that validates_format_of performs its validation on this pre-typecast value, so you don't need to specify that there.
EDIT
Sorry I was wrong about the "performs its validation on this pre-typecast value" part. Looking at the code of the validation, it calls .to_s on the post-typecast value which in your case returns "0" and therefore passes validation.
I'd suggest not bothering with this validation to be honest. If 0 is not a valid value for this column then validate that directly, otherwise just rely on the typecasting. If the user enters 123 foo you'll end up with 123 in the database which is usually just fine.
There is also better fitting validator for your case:
http://guides.rubyonrails.org/active_record_validations_callbacks.html#validates_numericality_of

Resources