0

I want to check if a record with the same value already exists in my model.

I have this create function in my trailer model,

def create
  trailer = Trailer.create(trailer_params)
  redirect_to :root
end

All the trailer records have a movie_id value. So without the check something like this can happen,

{"id":9,"movie_id":"5","link":"LsjX5dqHLuw"},    
{"id":10,"movie_id":"5","link":"LsjX5dqHLuw"}]

2 records with the same link and the same movie_id value.

So I was hoping it's possible to check if a record with the movie_id value already exists. If so, don't do anything. Else create the record.

I've done some research and created this, but this always goes to the else state.

def create
  if Trailer.exists?(:movie_id => :movie_id).present?
    trailer = Trailer.create(trailer_params)
    redirect_to :root
  else
    redirect_to :root
  end
end
5
  • 1
    Could you use find_or_create_by? Commented Jan 8, 2016 at 19:58
  • 1
    vee is right, it is better approach. Also you should be aware of the race condition: it is possible to create two similar objects by the two independent threads. Commented Jan 8, 2016 at 20:09
  • @vee how would you include parameters in a find_or_create_by? Because the record is being created, but it's empty. ` private def trailer_params params.require(:trailer).permit( :link, :movie_id ) end` Commented Jan 8, 2016 at 20:21
  • To answer myself Trailer.find_or_create_by(movie_id: params[:movie_id], link: params[:link]) seems to do the trick. Commented Jan 8, 2016 at 20:33
  • @vee if you want, you can answer the question so I can upvote you for your insights. Otherwise I'll provide the answer myself for clarity. Commented Jan 8, 2016 at 20:46

2 Answers 2

1

You could use first_or_create so:

trailer = Trailer.first_or_create(trailer_params)

This will either get you the first one with those params or create it if it doesn't exist. http://guides.rubyonrails.org/v3.2.9/active_record_querying.html#first_or_create

Sign up to request clarification or add additional context in comments.

Comments

1

Why don't you use ActiveRecord's uniqueness validator? http://guides.rubyonrails.org/active_record_validations.html#uniqueness

You can use it like so

# your Trailer model
class Trailer < ActiveRecord::Base
  validates :movie_id, uniqueness: true
end

# Then your controller may look like
def create
  Trailer.create(trailer_params)
  redirect_to :root
end

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.