Matteo Matteo - 7 months ago 18
Ruby Question

undefined local variable or method `recipient_email'

I'm trying to force a flash method out of my model so I can display something nicer than the standard rails error.

I have this method in my model,

invitation.rb
:

def recipient_is_not_registered
if User.find_by_email(recipient_email)
false
else
true
end
end


I call it with a
before_create :recipient_is_not_registered
callback and it returns false if the
recipient_email
has already been registered in the database as a User. This should trigger the
if @invitation.save
as false, which goes down the
else
branch, displaying the flash message.

In my
invitations_controller.rb
I have:

def create
@invitation = Invitation.new(invitation_params)
@invitation.sender = current_user
if @invitation.save
redirect_to root_url, notice: 'Invitation was successfully created.'
else
flash[:notice] = "The email address #{recipient_email} has already been registered."
end
end


This gives me the aforementioned error:
undefined local variable or method ``recipient_email'


I have tried various iterations of
Invitation.recipient_email
to no avail.

There are 2 questions.


  1. Resolve the NameError.

  2. Discover why the flash isn't being displayed.


Answer

You can try this:

def create
  @invitation = Invitation.new(invitation_params)
  @invitation.sender = current_user
  if @invitation.save
    redirect_to root_url, notice: 'Invitation was successfully created.'
  else
    flash[:notice] = "The email address #{@invitation.recipient_email} has already been registered."
  end
end

I hope this help you.

Comments