Rails - Validate Presence Of Association? Rails - Validate Presence Of Association? ruby-on-rails ruby-on-rails

Rails - Validate Presence Of Association?


You can use validates_presence_of http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_presence_of

class A < ActiveRecord::Base  has_many :bs  validates_presence_of :bsend

or just validateshttp://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates

class A < ActiveRecord::Base  has_many :bs  validates :bs, :presence => trueend

But there is a bug with it if you will use accepts_nested_attributes_for with :allow_destroy => true: Nested models and parent validation. In this topic you can find solution.


-------- Rails 4 ------------

Simple validates presence worked for me

class Profile < ActiveRecord::Base  belongs_to :user  validates :user, presence: trueendclass User < ActiveRecord::Base  has_one :profileend

This way, Profile.create will now fail. I have to use user.create_profile or associate a user before saving a profile.


You can validate associations with validates_existence_of (which is a plugin):

Example snippet from this blog entry:

class Tagging < ActiveRecord::Base  belongs_to :tag  belongs_to :taggable, :polymorphic => true  validates_existence_of :tag, :taggable  belongs_to :user  validates_existence_of :user, :allow_nil => trueend

Alternatively, you can use validates_associated. As Faisal notes in the comments below the answer, validates_associated checks if the associated object is valid by running the associated class validations. It does not check for the presence. It's also important to note that a nil association is considered valid.