Rails:如何在我的嵌套模型中使用find_or_create_by

时间:2016-03-16 14:59:22

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

模型:我有一个angular.module('showcase.withPromise', ['datatables', 'ngResource']).controller('WithPromiseCtrl', WithPromiseCtrl); function WithPromiseCtrl(DTOptionsBuilder, DTColumnBuilder, $resource) { var vm = this; vm.dtOptions = DTOptionsBuilder.fromFnPromise(function() { return $resource('data.json').query().$promise; }).withPaginationType('full_numbers'); vm.dtColumns = [ DTColumnBuilder.newColumn('id').withTitle('ID'), DTColumnBuilder.newColumn('firstName').withTitle('First name'), DTColumnBuilder.newColumn('lastName').withTitle('Last name').notVisible() ]; } 模型Company has_many。每个Tasks Task has_one

Employee型号:

Task

class Task < ActiveRecord::Base belongs_to :company has_one :employee, dependent: :destroy accepts_nested_attributes_for :employee validates_associated :noteholder end 型号:

Employee

表单:我为class Employee < ActiveRecord::Base belongs_to :task validates :name, presence: true, uniqueness: { case_sensitive: false } end Task模型的accepts_nested_attributes_for创建了一个嵌套表单。该表单包含Employee Employee字段,其name函数可加载所有autocomplete

Company.employees表格:

_form.html.erb

这为每位员工保存一条新记录,无论该员工是否存在

所需行为 如果用户填写新的<%= simple_form_for(@task) do |f| %> <%= f.simple_fields_for :employee do |employee| %> <%= employee.input :name, input_html: { data: { autocomplete_source: @employees.pluck(:name).to_json } } %> <% end %> <%= f.button :submit, 'Save' %> <% end %> ,则模型应创建新记录,而如果它将提供现有的Employee名称,则不应该。

我的尝试:我认为Employee方法在这里很有用,但实现它并没有成功。

问题:如何正确设置我的模型,如果员工find_or_create_by尚不存在,Employee模型只保存新员工?

0 个答案:

没有答案