未定义的局部变量或方法`recipient_email'

时间:2016-04-30 04:18:18

标签: ruby-on-rails ruby flash

我正在尝试从我的模型中强制使用flash方法,这样我就可以显示比标准rails错误更好的内容。

我的模型invitation.rb中有这个方法:

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

我使用before_create :recipient_is_not_registered回调调用它,如果recipient_email已作为用户在数据库中注册,则返回false。这应该将if @invitation.save触发为false,它会在else分支下方显示flash消息。

invitations_controller.rb我有:

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

这给我上述错误:undefined local variable or method ``recipient_email'

我尝试了Invitation.recipient_email的各种迭代但无济于事。

有两个问题。

  1. 解析NameError。
  2. 了解闪存未显示的原因。

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

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

我希望这对你有所帮助。

答案 1 :(得分:1)

根据您提供的信息,recipient_email的属性似乎是Invitation的属性,该属性仅在Invitation内可用。

尝试以下方法:

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