0

I want to create Job, Employer and Company using one form.

How to create a Job only if Job, Company and Employer are valid?

Model

class Job < ActiveRecord::Base
  accepts_nested_attributes_for :company, :employer 

  belongs_to :company
  belongs_to :employer

  validates :employer_id, presence: true, on: :update
  validates :company_id, presence: true

  def self.initialize_with_company(job_params)
    company_attributes = job_params.delete(:company_attributes)
    job_params.delete(:employer_attributes)

    new(job_params) do |job|
      job.company = Company.find_or_create_by_nip(company_attributes)
    end
  end

  def create_employer(employer_attributes)
    self.employer = Employer.create(employer_attributes)
  end
end

Controller

class JobsController < ApplicationController
  def new
    @job = Job.new
    if current_employer
      @job.company =  current_employer.companies.first
    else
      @job.company = Company.new
    end
    @job.employer = current_employer || Employer.new
  end

  def create
    employer_attributes = params[:job][:employer_attributes]
    @job = Job.initialize_with_company(params[:job])
    if current_employer
      @job.employer = current_employer
    else
      @job.create_employer(employer_attributes)
    end

    if @job.save
      if current_employer
        redirect_to dashboard_path
      else
        redirect_to jobs_path
      end
    else
      render 'new'
    end
  end
end

View

= simple_form_for @job do |f|
  ...
      = f.simple_fields_for :company do |c|
  ...
      = f.simple_fields_for :employer do |e|
  ...
    = f.button :submit
tomekfranek
  • 6,852
  • 8
  • 45
  • 80
  • http://stackoverflow.com/questions/1231608/rails-user-input-for-multiple-models-on-a-single-form-how – SG 86 Jan 10 '13 at 17:16
  • more helpful discussions... http://stackoverflow.com/questions/935650/accepts-nested-attributes-for-child-association-validation-failing – Mark Swardstrom Jan 10 '13 at 17:33

1 Answers1

0

You can use the ActiveRecord validates_associated method thusly:

  validates_associated :employer
  validates_associated :company

Be aware, it is possible to create a recursive loop of dependent models if you do validates_associated :job in one of the other models. Avoid this.

Daniel Evans
  • 6,788
  • 1
  • 31
  • 39
  • Ok, thx looks fine, but how then to prevent creating ``Employer`` when other models are not valid? – tomekfranek Jan 10 '13 at 18:16
  • You can prevent the Employer from being created when other models are not valid using the validates associated, just be very careful not to use it to create a circular dependency. If you need to, you can write a custom validator that handles it for your particular situation. – Daniel Evans Jan 10 '13 at 18:20