Skip to content

Instantly share code, notes, and snippets.

@cmdr-rohit-bang
Last active February 5, 2021 12:21
Show Gist options
  • Save cmdr-rohit-bang/72bb4937a33e07f1add5bc6c21d11e55 to your computer and use it in GitHub Desktop.
Save cmdr-rohit-bang/72bb4937a33e07f1add5bc6c21d11e55 to your computer and use it in GitHub Desktop.
Using Google reCaptcha in Project

Install this gem in project

gem 'recaptcha', require: 'recaptcha/rails'

Get Recaptcha Pubic and Secret keys from Google Recaptcha Admin and Put the keys vars in your .env file

STRIPE_PUB_KEY='pk_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxSTuV'
STRIPE_SEC_KEY='sk_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxWXYz'

Inside <%= form_for(:contact_inquiry) %> tag, use the the following syntax for recaptcha tag

<%= recaptcha_tags %>

In Controller function

def send_inquiry
  @inquiry = Inquiry.new(inquiry_params)
  @inquiry.captcha = verify_recaptcha
  if @inquiry.save
    redirect_to root_path, notice: 'Inquiry was successfully submitted.'
  else
    render :contact
  end
end

For Model Validation

class Inquiry < ApplicationRecord
  attr_accessor :captcha
  validate :recaptcha_validation, on: :create
  
  def recaptcha_validation
    errors.add(:captcha, 'Verification Failed, Please try again.') unless captcha
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment