Progger
Progger

Reputation: 35

change behaviour of Create if record with same attribute exists

I'm building an app like reddit where you add a Submission to a specific user page. Submission has a few attribute including an attribute called url. I want to check when adding a new submission if already a submission with that same url exists for that specific page, and if it exist, vote for it instead of creating it as a new submission. If not, just add it as a new submission. I'm using the act_as_votable gem here.

Here is the create method:

def create
    @user = User.friendly.find(params[:user_id])
    @submission =  @user.submissions.new(submission_params)
    @submission.member_id = current_user.id
    @submission.creator_id = @user.id
    @submission.is_viewed = false
    @submission.get_thumb_and_title_by_url(@submission.url)
    respond_to do |format|
       if @submission.save

        format.html { redirect_to @user, notice: 'Submission was 
 successfully created.' }
        format.json { render :show, status: :created, location: @submission }
       else
           format.html { render :new }
           format.json { render json: @user.errors, status: :unprocessable_entity }
       end
     end
  end

Upvotes: 0

Views: 42

Answers (1)

MZaragoza
MZaragoza

Reputation: 10111

you should take a look at https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by and https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_initialize_by

Now on your code we can make changes like

def create
    @user = User.friendly.find(params[:user_id]) 
    @submission =  @user.submissions.find_or_initialize_by(submission_params)
    if @submission.id.present? 
      # What to do if the record exists 
    else
      # if its a new record 
      @submission.member_id = current_user.id
      @submission.creator_id = @user.id
      @submission.is_viewed = false
      @submission.get_thumb_and_title_by_url(@submission.url)
    end


    respond_to do |format|
       if @submission.save

        format.html { redirect_to @user, notice: 'Submission was 
 successfully created.' }
        format.json { render :show, status: :created, location: @submission }
       else
           format.html { render :new }
           format.json { render json: @user.errors, status: :unprocessable_entity }
       end
     end
  end

I hope that this can put you on the right track

Happy Coding

Upvotes: 1

Related Questions