How to create a new record or update if a particular record based on an attribute other than record id exists, Ruby on Rails?

烈酒焚心 提交于 2019-12-12 05:12:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!