如何使用一个表单创建3个对象只有它们有效?

时间:2013-01-10 17:11:11

标签: ruby-on-rails ruby nested-forms nested-attributes

我想使用一种表格创建工作,雇主和公司。

如果JobJobCompany有效,如何创建Employer

模型

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

控制器

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

查看

= simple_form_for @job do |f|
  ...
      = f.simple_fields_for :company do |c|
  ...
      = f.simple_fields_for :employer do |e|
  ...
    = f.button :submit

1 个答案:

答案 0 :(得分:0)

您可以这样使用ActiveRecord validates_associated method

  validates_associated :employer
  validates_associated :company

请注意,如果您在其他模型中执行validates_associated :job,则可以创建依赖模型的递归循环。避免这种情况。