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
find_or_create_by?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`Trailer.find_or_create_by(movie_id: params[:movie_id], link: params[:link])seems to do the trick.