LoginSignup
7

More than 5 years have passed since last update.

RailsのGemを使ったEmailの判定

Posted at

Email-valodationの使用

Railsに備えられている様々なGemを使うことによってモデルに記述一行記述するだけでmodelに新しく作られる:emailの中身が正しいEmailかどうか判断してくれるGemがある

Git
stackoverflow

使用方法

まずはgemの追加

gem
gem 'email_validator'

次にbundleのインストールを実行して追加する

$  bundle install

modelの中に以下の記述を加える

model
validates email: true

これだけで新しくmodelを作る際に:emailの中身が正しいemailでは無かった場合生成されなくなる

これを利用すればControllerでemailが正しく使われた場合と使われなかった場合で表現方法を変えることが出来る

controller
def create
    @email = params[:email]
    @newmodel = EmployeeInvitation.new
    @newmodel.company_id = current_company
    @newmodel.email = @email
    if @newmodel.save              #ここでemailが正しくない場合はfalseになる
    EmployeeInvitationMailer.delay.new_invitation(@email, current_company)
    flash[:notice] = I18n.t("company.complete_invitaion")
    else
    flash[:notice] = "正しいEmailを入力してください"
    end
    redirect_to enterprise_users_path
  end

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7