how to validate associated model id?
You should look into creating a custom validation method:
class Student < ActiveRecord::Base
validates :course_id, presence: true, numericality: { only_integer: true }
...
validate :validate_course_id
private
def validate_course_id
errors.add(:course_id, "is invalid") unless Course.exists?(self.course_id)
end
end
First, your model will make sure that the course_id
is a valid integer, and then your custom validation will make sure that the course exists in the database.
Validating associated models in Rails
Try:
validates :measurement, inclusion: { in: ->(record) { record.food.measurements } }
validates
is a method defined on a class, and is being evaluated when a class is declared. Normally, when inclusion values are known before program starts (and are static), passing value is sufficient - validator (which is being created when validates
is called) simply saves the passed object and uses it when validating.
In your case the inclusion values are unknown at the point when validator is created (and they also depends on the validating object). Hence, you need to pass a lambda, so validator can use it to get inclusion values during a runtime.
Note also, that validator object is attached to a class, not to a particular instance, so lambda needs to have record param.
How do I validate an association value is present in Rails?
Please try using custom validation
class User < ApplicationRecord
validate :company_aum_id_present, if: :provider?
private def company_aum_id_present
self.errors[:aum_id] << 'Assets Under Management is required.' if company && company.aum_id.blank?
end
end
Also When usin custom validator you dont need to include ActiveModel::Validations
as it is already included by ApplicationRecord
Ruby on Rails - Validate attribute with Associated Model attribute
You will need to add custom validation
class ModelA < ActiveRecord::Base
has_many: :model_b
end
class ModelB < ActiveRecord::Base
belongs_to : model_a
validates :is_between_parent_period
private
def is_between_parent_period
unless start_date.between?(self.model_a.start_date, self.model_a.end_date) && end_date.between?(self.model_a.start_date, self.model_a.end_date)
errors.add(:base, 'Must be between parent start date and end date')
end
end
end
Rails 4: Difference between validates presence on id or association
Investigating further, I found that the 'presence' validator resolves to 'add_on_blank':
http://apidock.com/rails/ActiveModel/Errors/add_on_blank
def add_on_blank(attributes, options = {})
Array(attributes).each do |attribute|
value = @base.send(:read_attribute_for_validation, attribute)
add(attribute, :blank, options) if value.blank?
end
end
This does what it says: adds a validation error if the property in question is blank?
This means it's simply an existence check. So if I validate an id, that id has to exist. That means:
topping.pancake = Pancake.new
topping.valid?
would return false. However:
topping.pancake_id = -12
topping.valid?
would return true. On the other hand, if I validate the object the exact opposite would be true. Unless -12 is a valid index, in which case ActiveRecord would automatically load it from the database on receipt of the 'pancake' message.
Moving on to my issue, further investigation showed that blank?
delegates to empty?
, and indeed someone had defined empty?
on the pancake, returning true if there are no toppings.
Culprit found, and something about Rails learned.
Related Topics
Get Substring After the First = Symbol in Ruby
Installing Gem Fails with Permissions Error
Rails -- Create and Create! Methods, Ror 3 Tutorial
How to Install Gems with Apt-Get on Ubuntu
How to Debug/Display Request Sent Using Restclient
Ruby 'Each_With_Object' with Index
Cool Tricks and Expressive Snippets with Ruby Collections/Enumerables
Rails Activeadmin: Showing Table of a Related Resource in the Same View
Loop Through Activerecord::Associations::Collectionproxy with Each
Context Aware Authorization Using Cancan
How to Split String Across New Lines and Keep Blank Lines
How to Force Activerecord to Reload a Class
Carrierwave Crop Specific Version
Ruby: How to Make a Public Static Method
Generating Unique Token on the Fly with Rails