Home > Mobile >  How to apply if exists update else create in ruby on rails?
How to apply if exists update else create in ruby on rails?

Time:08-16

I am new to ruby on rails and i want to apply if exists update or create in the database. Currently it is creating a new row everytime. How it can be done?

Here is "gmatches_controller.rb" (Controller):

class GmatchesController < ApplicationController

    def savedata
        @match = Gmatch.new(match_params)

        if @match.save
            redirect_to root_path
        else 
            render 'index'
        end
    end


    private

    def match_params
        params.permit(:tournament_id, :player_name, :played_with, :start_date, :winner_name)
    end
end

CodePudding user response:

Try using find_or_initialize_by:

# replace
# @match = Gmatch.new(match_params)

@match = Gmatch.find_or_initialize_by(match_params)

# now @match will either be a new record, or a persisted record
# @match.new_record?
# @match.persisted?

if @match.new_record?
  # do something if it's brand new (like save it)
else
  # do something if it already existed (like update it)
end
  • Related