Reputation: 7
My invite form is not being saved. There are no errors. The mailer is not being sent and I am not being redirected to the root path.
Invites Controller:
class InvitesController < ApplicationController
def new
@invite = Invite.new
end
def create
@invite = Invite.new(invite_params)
if @invite.save
InviteMailer.invite_user(@invite).deliver_now
flash[:success] = "You have successfully sent an invite"
redirect_to root_path
else
render 'new'
end
end
private
def invite_params
params.require(:invite).permit(:email)
end
end
Invites Model:
class Invite < ApplicationRecord
belongs_to :user
end
Invites new View:
<h1>Invite your friend!</h1>
<%= form_for @invite , :url => userinvite_path do |f| %>
<%= f.label :email %>
<%= f.email_field :email %>
<%= f.submit "Send" %>
<% end %>
Invites Mailer:
class InviteMailer < ApplicationMailer
def invite_user(invite)
@invite = invite
mail to: invite.email, subject: "Invitation to Math-Scientist"
end
end
Application Mailer:
class ApplicationMailer < ActionMailer::Base
default from: '[email protected]'
layout 'mailer'
end
Mailer View (Text): Hi, You have been invited to join Math-Scientist by your friend. Sign up now: https://math-scientist.herokuapp.com/usersignup Hope you enjoy our product!
Routes File:
Rails.application.routes.draw do
root 'static_pages#home'
get '/usersignup', to: 'users#new'
get '/companysignup', to: 'companies#new'
get '/userlogin', to: 'sessions#new'
post '/userlogin', to: 'sessions#create'
delete '/userlogout', to: 'sessions#destroy'
get '/userinvite', to: 'invites#new'
post '/userinvite', to: "invites#create"
resources :users
resources :companies
resources :invites
end
Upvotes: 1
Views: 68
Reputation: 50057
My guess the invite is not being saved because you have a belongs_to :user
relationship. Since rails 5 this is by default required. This means that either you have to set the user_id
before saving, or specify it is optional.
Do not set it the user-id the form (in a hidden field), because this enables tampering (e.g. someones edits the form before submitting it).
So in your controller you can do something like
@invite = Invite.new(invite_params)
@invite.user_id = current_user.id
if @invite.save ...
or, if the user
is not really required you could also adapt your model
belongs_to :user, optional: true
Upvotes: 1