![](/img/trans.png)
[英]Ruby/Rails worker to create or update record if exists - avoid DRY
[英]How to create a new record or update if a particular record based on an attribute other than record id exists, Ruby on Rails?
我有2个模特班,员工和公司。 外部库仅生成员工ID。 如果他的详细信息已经存在,我正在尝试更新他的详细信息,否则我需要创建一个新的雇员详细信息。 以下是create方法的代码:
def create
if !@emp= Details.find_or_create_by_emp_id(params[:details][:emp_id])
@emp = Details.new(params[:details])
// some logic goes here
else
@emp.update_attributes(params[:details])
render action: "show"
end
end
但这总是使用现有的emp_id创建一条新记录,而不是更新与特定emp_id相关的表行。 如何使其工作?
您可以尝试以下方法:
def create
@emp = Details.find_by_emp_id(params[:details][:emp_id])
if @emp
@emp.update_attributes(params[:details])
render action: "show"
else
@emp = Details.new(params[:details])
//other stuff
end
end
因此,如果员工已经存在,则将其设置为@emp,否则将@emp设置为nil
您使用的是find_or_create错误。 它同时包含标识符和哈希:
if Detail.find_or_create_by_emp_id(params[:detail][:emp_id], params[:detail])
#success
else
#fail
end
注意:您的Model名称和param似乎都是复数形式,这与惯例相反,您确定这就是您想要的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.