Email-valodationの使用
Railsに備えられている様々なGemを使うことによってモデルに記述一行記述するだけでmodelに新しく作られる:emailの中身が正しいEmailかどうか判断してくれるGemがある
使用方法
まずは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