Jest możliwość użyć find_or_create wraz z nested attributes?

Chciałbym uzyskać taką funkcjonalność.

Tworząc nową ofertę pracy, podaję nip firmy i kiedy firma o tym nipie istnieje w bazie zostaje przypisana do tej oferty pracy a kiedy nie zostaje utworzona.

[code=ruby]# JobsController
def new
@job = Job.new
@job.company = Company.new
end

def create
@job = Job.new(params[:job])

if @job.save
@job.company = Company.where(nip: params[:job][:company_attributes][:nip]).first_or_create
redirect_to jobs_path,
notice: t(‘activerecord.successful.messages.created’)
else
render ‘new’
end
end

Job

attr_accessible :company_attributes
belongs_to :company
accepts_nested_attributes_for :company

Company

has_many :jobs
validates :nip,
nip: true,
presence: true,
uniqueness: true
View

View: jobs#new

= simple_form_for @job, html: { multipart: true, class: ‘form-horizontal’ } do |f|
= f.simple_fields_for :company do |c|
= c.input :nip
= c.input :address_street
= f.submit[/code]
W powyższym przypadku otrzymuję błąd

pl.activerecord.errors.models.company.attributes.nip.taken

może coś takiego?

[code=ruby]# model
class Job < ActiveRecord::Base
def self.create_with_company(job_params)
company_attributes = job_params.delete(:company_attributes)

new(job_params) do |job|
  job.company = Company.find_or_initialize_by_nip(company_attributes[:nip])
end

end
end

controller

def create
@job = Job.create_with_company(params[:job])

if @job.save
redirect_to jobs_path, notice: t(‘activerecord.successful.messages.created’)
else
render :new
end
end[/code]

Nie jestem pewien, ale jak to problem z validacja, przy nested_attributes to moze pomoze ,inverse_of’’

[code=ruby]# Job
attr_accessible :company_attributes
belongs_to :company, inverse_of: :jobs
accepts_nested_attributes_for :company

Company

has_many :jobs, inverse_of: :company
validates :nip,
nip: true,
presence: true,
uniqueness: true[/code]

Użyłem podpowiedzi zlw

[code=ruby] def self.create_with_company_and_employer(job_params)
company_attributes = job_params.delete(:company_attributes)
employer_attributes = job_params.delete(:employer_attributes)

new(job_params) do |job|
  job.employer = Employer.find_or_create_by_email(employer_attributes)
  company_attributes[:admin_id] = job.employer.id if Company.find_by_nip(company_attributes[:nip]).nil?
  job.company = Company.find_or_create_by_nip(company_attributes)
  Employment.create(employer_id: job.employer.id, company_id: job.company.id)
end

end[/code]
tyle, że aby wyświetlić błędy walidacji dla Company zmieniłem na find_or_create_by_nip.

Zastanawiam się czy można coś jeszcze z tym zrobić.