创建员工后,将为其授予标题。如果标题是唯一的,则记录将正常保存。如果标题不是唯一的,我想找到现有的标题,并改用它。我不知道如何在create动作中做到这一点。
雇主
class Employee < ActiveRecord::Base
belongs_to :title, :class_name => :EmployeeTitle, :foreign_key => "employee_title_id"
accepts_nested_attributes_for :title
end
loyal_title.rb
class EmployerTitle < ActiveRecord::Base
has_many :employees
validates :name, presence: true, length: { maximum: 50 },
uniqueness: { case_sensitive: true }
end
new.html.erb
<%= f.simple_fields_for :title do |title| %>
<%= title.input :name, label: "Title" %>
<% end %>
employee_controller.rb
def create
if EmployeeTitle.exists?(name: employee_params[:title_attributes][:name])
# find title and use it?
else
@employee = current_user.employee.build(employee_params)
end
if @employee.save
flash[:success] = "Employee #{@employee.title.name} created."
redirect_to @employee
else
render 'new'
end
end
编辑:使用first_or_create
def create
EmployeeTitle.where(name: employee_params[:title_attributes][:name]).first_or_create do |title|
@employee = current_user.employees.build(employee_params, :title => title)
end
if @employee.save
flash[:success] = "Employee #{@employee.title.name} created."
redirect_to @employee
else
render 'new'
end
end
这使@employee超出范围。错误:nil:NilClass的未定义方法“保存”。
此外,如果我这样做,则无论其余员工数据是否有效,都不会创建标题吗?
使用私有方法
employee.rb
private
def title_attributes=(attributes)
self.title = EmployeeTitle.find_or_create_by_name(name: attributes[:name])
end
尚未设置该值。我收到“不能为空”的验证错误。参数包括
employee: !ruby/hash:ActionController::Parameters
title: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
name: Consultant
!ruby / hash:ActiveSupport :: HashWithIndifferentAccess以前不存在。
employee_params
private
def employee_params
params.require(:employee).permit(
title_attributes: [:id, :name],
)
end
您需要做的是更改此设置:
def create
if EmployeeTitle.exists?(name: employee_params[:title_attributes][:name])
# find title and use it?
else
@employee = current_user.employee.build(employee_params)
end
if @employee.save
flash[:success] = "Employee #{@employee.title.name} created."
redirect_to @employee
else
render 'new'
end
end
有了这个:
def create
@employee = current_user.employee.build(employee_params)
if @employee.save
flash[:success] = "Employee #{@employee.title.name} created."
redirect_to @employee
else
render 'new'
end
end
现在,title_attributes
通过将以下代码放在您的app / models / employee.rb文件中来覆盖方法:
def title_attributes=(attributes)
self.title = EmployeeTitle.find_or_create_by_name(attributes[:name])
end
现在,每次您创建一个名称已经与特定名称一起存在的员工时,默认情况下将使用该员工将其与关联title
。让控制器像以前一样瘦。
find_or_create_by
在此处阅读有关方法的更多信息。
但是,您的问题标题是:Rails 4,但您已标记ruby-on-rails-3.2。如果您使用的是Rails 4,则可以改用以下方法:
EmployeeTitle.find_or_create_by(name: attributes[:name])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句