[英]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.