如何在Rails中将nested_attributes与find_or_create_by进行比较?

时间:2012-11-17 19:51:36

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

我希望能够使用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

1 个答案:

答案 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