donkey
donkey

Reputation: 4363

How do I disallow saving objects unless its associations are set?

I want to make sure that my Staff object cannot save without its Profile is created.

Is there any validation I can set to achieve this?

Staff.rb:

class Staff < ActiveRecord::Base
  has_one :profile
end

Profile.rb:

class Profile < ActiveRecord::Base
   belongs_to :staff
end

Upvotes: 1

Views: 26

Answers (1)

Ilya
Ilya

Reputation: 13477

Use validations (it works with this association):

class Staff < ActiveRecord::Base
  has_one :profile

  validates :profile, presence: true
end

Or just:

validates_presence_of :profile

Upvotes: 4

Related Questions