2013-01-10 48 views
0

我想用一種形式創建Job,Employer和Company。如何使用一種形式創建3個對象,只有它們有效?

如何創建Job僅當Job,CompanyEmployer有效?

型號

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 
+0

http://stackoverflow.com/questions/1231608/rails-user-input-for-multiple-models-on-a-single-form-how –

+0

更有幫助的討論... http://stackoverflow.com/questions/935650/accept-nested-attributes-for-child-association-validation-failing – Swards

回答

0

可以使用ActiveRecord validates_associated method正是如此:

validates_associated :employer 
    validates_associated :company 

要知道,這是可能的,如果您在其他車型的一個做validates_associated :job建立相關模型遞歸循環。避免這種情況。

+0

好吧,thx看起來不錯,但是如何防止在其他模型無效時創建''Employer''? – tomekfranek

+0

當其他模型使用關聯的驗證無效時,您可以防止創建僱主,只需非常小心,不要使用它來創建循環依賴關係。如果你需要,你可以寫一個自定義驗證器來處理你的特定情況。 –

相關問題