问题描述
我有2个模型类,员工和放大器;公司。只有雇员标识是由一个外部库产生。我想更新员工的详细信息,如果他的详细信息已经存在,否则我需要建立一个新员工的详细信息。以下是$ C $下创建的方法:
I have 2 model classes, employee & company. Only an employee id is generated by an external library. I am trying to update an employee details if his details already exist, else I need to create a new employee details. following is the code for create method:
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表行的新纪录。如何使它工作?
But this always creates a new record with existing emp_id, rather than updating the table row pertaining to a specific emp_id. How to make it work ?
推荐答案
您可以试试这个:
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设为零
So if the employee already exists it's set to @emp, otherwise @emp is set to nil
这篇关于如何创建一个新的记录或更新,如果特定记录基于属性以外存在的记录ID,Ruby on Rails的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!