views:

12

answers:

1

I have a resume model that has two associations (documents and wizards). A document is the uploaded resume while a wizard is the output from the user using the resume wizard. These are mutually exclusive models. How can I validate that the user has created a document or a wizard when validating resume?

I am building the association in my resume controller as such.

if params[:document]
  @document = @resume.build_document(params[:document])
else
  @wizard = @resume.build_wizard(params[:wizard])
end

Then I either do a resume.save or resume.update_attributes(params[:resume]).

+1  A: 

Use polymorphic has_one/belongs_to. Then you can just assign documented attribute to your Resume object:

class Resume < ActiveRecord::Base
  belongs_to :documented, :polymorphic => true

  # this line validates the presence of associated object (Wizard or Document)
  validates_associated :documented
end

class Document < ActiveRecord::Base
  has_one :resume, :as => :documented
end

class Wizard < ActiveRecord::Base
  has_one :resume, :as => :documented
end

>> document = Document.create(...)
>> resume = Resume.find(...)
>> resume.documented = documented
>> resume.save!
>> resume.documented.class # => Document
>> wizard = Wizard.create(...)
>> resume.documented = wizard
>> resume.save!
>> resume.documented.class # => Wizard
Eimantas
Technically the resume is the parent.
Jared Brown
How would the validation look?
Jared Brown
Updated the code with validation for wizard or document.
Eimantas