Sachin Prasad
Sachin Prasad

Reputation: 5411

Insert or update with find_or_create_by_id

This is what I'm doing:-

@userdata =find_or_create_by_id(:id=>params[:id])

Now how can I know weather I need to use @userdata.save or

@userdata.update_attributes params[:user_object]

And how to pass my user object in case of @userdata.save

Upvotes: 0

Views: 269

Answers (3)

boulder
boulder

Reputation: 3266

Not sure what you mean by whether to user save or update_attributes. find_or_create_by_id will return a user object, that may or may not be persisted depending on whether validations passed (if it didn't exist already). You can find out by asking @userdata.persisted?

In any case, I recommend using first_or_create:

@userdata = User.where(:id => params[:id]).first_or_create(params[:user_object])
if @userdata.persisted? 
  # proceed
else
  # errors in params, recover
end

UPDATE: Kiddorails is right about the above code not updating the record if it existed prior to the call. The solution is actually pretty simple. Sorry I didn't get it right the first time:

@userdata = User.where(:id => params[:id]).first || User.new
@userdata.update_attributes(params[:user_object])

This works because update_attributes works just fine whether the record is new or persisted.

Upvotes: 3

Try this. The first line search object and create if doesn't exist.

   userdata = UserModel.where(:id=>params[:id]).first_or_create(:id=>params[:id])
    unless userdata .nil?
      update_attributes params[:user_object]
    end

Upvotes: 1

kiddorails
kiddorails

Reputation: 13014

Perhaps, this can help:

@userdata = User.find_or_create_by_id(params[:id])
if @userdata.new_record? #=> @userdata is a new record
  #Add attributes
  @userdata.save
else
  @userdata.update_attributes params[:user_object]
end

Or even better, make your own method as Best way to find_or_create_by_id but update the attributes if the record is found

Upvotes: 1

Related Questions