我希望能够使用Company.find_or_create_by_nip(params[:job][:company_attributes])
。
当我想使用嵌套的公司表单创建Job
时,我想首先检查Company
是否存在nip
,然后将其分配给新的Job
< / p>
控制器的
# JobsController
def new
@job = Job.new
@job.company = Company.new
end
def create
@job = Job.new(params[:job])
if @job.save
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
视图的
# 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
答案 0 :(得分:1)
也许你应该尝试if条件:
nip = params[:job][:company_attributes][:nip]
if Company.exists?(name: nip)
@job.company = Company.where(name: nip).first
else
@job.company = Company.create(name: nip)
end