Rails 3 validates inclusion of when using a find (how to proc or lambda)
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
Which is better to use in Rails model validation: Proc or lambda?
The only difference I can think of would be a possibility to use early returns from λs. That said, the former would happily validate, while the latter would raise LocalJumpError
:
validates :name, present: true,
if: -> { return false unless assotiation; assotiation.present? }
validates :name, present: true,
if: proc { return false unless assotiation; assotiation.present? }
Also, I use the following rule of thumb: strict is better than wide-open. So unless it’s absolutely definite that you need a proc
, λ is the better tool to use everywhere.
Rails validation variable proc
You're looking for a custom validation method:
ActiveRecord::Base.class_eval do
def self.validates_max_passenger(attr_name, r)
validates attr_name, :inclusion => { :in => r, :min => r.first, :max => r.last } }
end
end
# later in your class of choice:
validates_max_passenger :passengers, 1..5
Or, you can try the following with lambda
def self.max_passengers
1..15
end
validates :attrib, :inclusion => {:in => lambda { |obj| ClassName.max_passengers } }
Note that you won't need the min/max if you're using :in
on range.
How to validates with proc in rails
I prefer to validate format with validates
and put such logic as your into validate
methods:
validates :price, allow_nil: true, numericality: { only_integer: true, less_than: 1000000 }
validate :price_amount
def price_amount
if only_rental?
price.zero?
else
price.positive?
end
end
also you could use Rails' with_options
:
with_options allow_nil: true, numericality: { only_integer: true, less_than: 1000000 } do
validates :price, numericality: { greater_than: 0 }, unless: :only_rental?
validates :price, numericality: { in: [0] }, if: :only_rental?
end
validates array elements inclusion using inclusion: { in: array }
The standard inclusion validator will not work for this use case, since it checks that the attribute in question is a member of a given array. What you want is to check that every element of an array (the attribute) is a member of a given array.
To do this you could create a custom validator, something like this:
VALID_INTERESTS = ["music","biking","hike"]
validate :validate_interests
private
def validate_interests
if (invalid_interests = (interest_list - VALID_INTERESTS))
invalid_interests.each do |interest|
errors.add(:interest_list, interest + " is not a valid interest")
end
end
end
I'm getting the elements of interest_list
not in VALID_INTERESTS
by taking the difference of these two arrays.
I haven't actually tried this code so can't guarantee it will work, but the solution I think will look something like this.
validates_inclusion_of Rails 3 with a query not working as expected
It's not working as you want because the :in => Account.find(:all).collect(&:id)
it's evaluated just one time in production mode, when Rails loads the class. I confess I don't understand the reason behind such a validation. Anyway, you have to use a custom validator if you really want to achieve that.
validates_inclusion_of no longer working the same in Rails 4.1?
try adding .keys
?
validates :time_zone,
inclusion: {
in: ActiveSupport::TimeZone.zones_map.keys
}
Rails validate model attribute based on value of another attribute
You can use a proc or lambda object which gets the current user instance. This instance you can ask for the state. The proc or lambda should return an enumerable with all valid cities.
adapted from the rails v3.2 api:
validates :city, presence: true, inclusion: { :in => lambda{ |user| CS.cities(user.state.to_sym, :in) }}
Related Topics
Gem Not Found in Ruby Cron Job in Rvm Env
Setting Up Facets in Elasticsearch with Searchkick Gem in Rails 4.1
Ruby: How to "Require" a File from the Current Working Dir
How to Format a String with Floats in Ruby Using #{Variable}
How to Expect Some (But Not All) Arguments with Rspec Should_Receive
Why Isn't My Cocoapods Post_Install Hook Updating My Preprocessor MACros
How to Profile Ruby 1.9.2 Scripts with Memory Allocation Reports
Using Nokogiri HTML Builder to Create Fragment with Multiple Root Nodes
Sudo Gem Install Pg Won't Work
Simple_Form's Collection_Radio_Button and Custom Label Class
Learning Ruby: Recommended Blogs to Read
Counting Days Excluding Weekends
Rubocop Error 'Class Definition Is Too Long Ruby'