In an initializer I have a huge COUNTRY_CODES hash, with format:
{ :us => "United States, :de => "Germany" }
In my model I want to validate that the entered value is:
present
a key of my country code hash
How do I apporach this?
I can't use:
validates :country, :presence => true,
:inclusion => { :in => COUNTRY_CODES }
I've tried custom validators, but I get method errors when the value is nil, e.g. when I try to use value.to_sym, causing me to validate the validator and it becomes messy.
Trying to figure out the most DRY and efficient way of doing this.
You need to collect COUNTRY_CODES keys(symbols) as strings and validate for the inclusion. So use:
validates :country, :presence => true,:inclusion => { :in => COUNTRY_CODES.keys.map(&:to_s) }
Try COUNTRY_CODES.keys if you only want to check with the keys in the hash.
Hows this?
validates :country, :presence => true,
:inclusion => { :in => COUNTRY_CODES.keys.map{|c| c.to_s}
Related
I have a Rails App and I am using an EachValidator method to check the length of the attribute and showing the error according to limit
the validation goes like this
validates :name, :presence => {
:message => 'Please enter name'
}, :string => self.columns_hash["name"].type
now in the :string custom Validation I am right now passing the datatype of the name column, but i want to pass the datatype length instead. How can i achieve this ?
Please try this,
validates :name, :presence => {
:message => 'Please enter name'
}, :length => {
:maximum => columns_hash['name'].limit
}
Let me know if it is working fine.
validates :name, :presence => {
:message => 'Please enter name'
}, :length => { maximum: 255 } # 255 for a string data type
If I understand you correctly you, there is a gem available for this:
gem 'validates_lengths_from_database'
Then in your model simply put:
validates_lengths_from_database
Which will generate validations based on the schema for maximum lengths of string and text fields.
I figured a way to do validation. I found that inside models, i need to add these lines
validates_presence_of :name
validates_uniqueness_of :name
What i'm trying to achieve is for example, i don't want the user to add :;!##$%^&*() [or special characters] in my text inputs. Need some inputs on this.
You can use format_of:
validates_format_of :name, :with => /\A[a-zA-Z]+([a-zA-Z]|\d)*\Z/
Or create your own validation:
validates :name,
:presence => true,
:format => { :with => regex } # Here you can set a 'regex'
I want validate presence of these 2 attributes :shipping_cost and :shipping_cost_anywhere if the attribute :shipping is equal to true. and If
I have this in my model but not working fine for me:
validates_presence_of :shipping_cost, :shipping_cost_anywhere, :allow_blank => "true" if :shipping == "true"
this is my :shipping attribute:
field :shipping, :type => Boolean, :default => "false"
How can I do it?
Thank you!
Edited.
I'm using mongoid and simple_form gems
validates_presence_of :shipping_costs_anywhere, :if => :should_be_filled_in?
def should_be_filled_in?
shipping_costs_anywhere == "value"
end
The method will return true or false when it's called in the statement.
No need to put colon in front of shipping_costs_anywhere.
The fix for me to this question is the next code:
validates :shipping_cost, :shipping_cost_anywhere, :presence => true, :if => :shipping?
Thank you to all for your help but any answer has worked for me. thanks!
Stumbled across this today and thought I'd freshen the answer. As others mentioned, you can put the logic in a function. However, you can also just throw it in a proc.
validates_presence_of :shipping_costs_anywhere, :if => Proc.new { |o|
o.shipping_costs_anywhere == "value"}
http://guides.rubyonrails.org/active_record_validations.html#using-a-symbol-with-if-and-unless
The validates is now preferred over validates_presences_of etc. As hyperjas mentioned you can do this:
validates :shipping_cost,
:shipping_cost_anywhere,
:presence => true, :if => :shipping?
However, that conditionalizes the entire validation for both :shipping_cost and :shipping_cost_anywhere. For better maintainability, I prefer a separate validate declaration for each attribute.
More importantly, you will likely run into situations where you have multiple validations with different conditions (like one for presence and another for length, format or value). You can do that like this:
validates :shipping_cost,
presence: { if: :shipping? },
numericality: { greater_than: 100, if: :heavy? }
You can also let rails evaluate a ruby string.
validates :shipping_cost,
presence: { if: "shipping?" },
numericality: { greater_than: 100, if: "shipping? and heavy?" }
And finally, optionally add separate custom messages:
validates :shipping_cost,
presence: { if: "shipping?", message: 'You forgot the shipping cost.' },
numericality: { greater_than: 100, if: "shipping? and heavy?", message: 'Shipping heavy items is $100 minimum.' }
And so on. Hope that helps.
I can't test it, but I think the syntax is more like:
validates_presence_of :shipping_cost, :shipping_cost_anywhere, :allow_blank => "true", :if => "shipping.nil?"
See:
http://guides.rubyonrails.org/active_record_validations_callbacks.html#conditional-validation
Here is my code working for me.Call method on if condition rather than comparing
validates :prefix, :allow_blank => true, :uniqueness => { :case_sensitive => true } ,:if => :trunk_group_is_originating?
def trunk_group_is_originating?
if self.direction == "originating"
true
else
false
end
end
Hope it helps you.......
I validate fields in model using:
validates :first_name, :presence => true, :if => :should_validate?
validates :last_name, :presence => true, :if => :should_validate?
...
There are many fields in model that needs to be validated and it doesn't look good if I specify :if => method for each one.
Is it possible to embed this validates methods in block instead of giving :if => method for each one?
You could write your own custom validator of course, but if you're only validating presence, this might do the trick:
validates :first_name, :last_name, :presence => true, :if => :should_validate?
I don't think there is something out of the box for this. If you want, you can use a custom validator.
What are the conditions that you need this validated? If you don't need it validated couldn't you just leave that line out? Otherwise you could just validate on certain actions so you don't need to evaluate for should_validate?, for example:
validates :first_name, :last_name, :presence => true, :only => [:create, :update]
I've got a project where there is a CURRENCY and COUNTRY table. There's a PRICE model that requires a valid currency and country code, so I have the following validation:
validates :currency_code, :presence => true, :inclusion => { :in => Currency.all_codes }
validates :country_code, :presence => true, :inclusion => { :in => Country.all_codes }
The all_codes method returns an array of just the currency or country codes. This works
fine so long as no codes are added to the table.
How would you write this so that the result of the Currency.all_codes was either a Proc or inside a lambda? I tried Proc.new { Currency.all_codes } -- but then get an error that the object doesn't respond to include?
Just use a proc, like so:
validates :currency_code,
:presence => true,
:inclusion => { :in => proc { Currency.all_codes } }
validates :country_code,
:presence => true,
:inclusion => { :in => proc { Country.all_codes } }
It's worth noting for anyone else who may stumble across this that the proc also has the record accessible as a parameter. So you can do something like this:
validates :currency_code,
:presence => true,
:inclusion => { :in => proc { |record| record.all_codes } }
def all_codes
['some', 'dynamic', 'result', 'based', 'upon', 'the', 'record']
end
Note: This answer is true for old versions of Rails, but for Rails 3.1 and above, procs are accepted.
It must not accept Procs. You can use a custom validation method to do the same thing:
validate :currency_code_exists
def currency_code_exists
errors.add(:base, "Currency code must exist") unless Currency.all_codes.include?(self.currency_code)
end