Ruby on rails 4 Rails:如何在嵌套模型中使用find_或create_by
模型:我有一个Ruby on rails 4 Rails:如何在嵌套模型中使用find_或create_by,ruby-on-rails-4,nested-forms,nested-attributes,Ruby On Rails 4,Nested Forms,Nested Attributes,模型:我有一个公司模型,它有许多任务。每个任务都有一名员工 任务型号: class Task < ActiveRecord::Base belongs_to :company has_one :employee, dependent: :destroy accepts_nested_attributes_for :employee validates_associated :noteholder end class Employ
公司
模型,它有许多任务
。每个任务
都有一名员工
任务
型号:
class Task < ActiveRecord::Base
belongs_to :company
has_one :employee, dependent: :destroy
accepts_nested_attributes_for :employee
validates_associated :noteholder
end
class Employee < ActiveRecord::Base
belongs_to :task
validates :name, presence: true, uniqueness: { case_sensitive: false }
end
表单:我为任务
创建了一个嵌套表单,接受员工
模型的嵌套属性。表单有一个员工
姓名
字段,该字段具有一个自动完成
功能,可加载所有公司员工
\u 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 %>
这将为每个员工保存一条新记录,而不管是否存在同名员工
期望的行为:
如果用户填写一个新的员工
,则模型应创建一个新记录,而如果它将提供一个现有的员工
姓名,则不应创建新记录
我的尝试:我认为find\u或\u create\u by
方法在这里会很有用,但没有成功实现它
问题:如何正确设置我的模型,使员工
模型仅在员工名不存在时保存新员工?现在表单的行为是什么?它会创建任何对象吗?您可以在问题中发布表单的代码吗?请参阅上面的简单表单代码,它现在为每个员工保存一条新记录,而不管是否存在同名员工