问题
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
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 ?
回答1:
You could try this:
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
So if the employee already exists it's set to @emp, otherwise @emp is set to nil
回答2:
You're using find_or_create wrong. It takes both the identifier and the hash:
if Detail.find_or_create_by_emp_id(params[:detail][:emp_id], params[:detail])
#success
else
#fail
end
Note: both your Model name and param seems to be plural, that's against convention, are you sure that's what you intended?
来源:https://stackoverflow.com/questions/12012728/how-to-create-a-new-record-or-update-if-a-particular-record-based-on-an-attribut