Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Validate Presence Of Association?

I have a model A that has a "has_many" association to another model B. I have a business requirement that an insert into A requires at least 1 associated record to B. Is there a method I can call to make sure this is true, or do I need to write a custom validation?

like image 958
skaz Avatar asked Apr 16 '11 21:04

skaz


Video Answer


2 Answers

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 :bs end 

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

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

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.

like image 55
fl00r Avatar answered Oct 09 '22 09:10

fl00r


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

Simple validates presence worked for me

class Profile < ActiveRecord::Base   belongs_to :user    validates :user, presence: true end  class User < ActiveRecord::Base   has_one :profile end 

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

like image 29
hexinpeter Avatar answered Oct 09 '22 08:10

hexinpeter