简体   繁体   中英

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

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 ?

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM