0

我希望能够使用Company.find_or_create_by_nip(params[:job][:company_attributes]).

当我想Job使用嵌套的公司表单创建时,我想首先检查是否存在Companynip端,然后将其分配给那个新的Job

控制器

# 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
4

1 回答 1

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
于 2012-12-29T07:09:14.530 回答