未定义的局部变量或方法“recipient_email”

undefined local variable or method `recipient_email'

我试图从我的模型中强制使用 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 已经作为用户在数据库中注册,它 returns 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 的各种迭代都无济于事。

有2个问题。

  1. 解决 NameError。
  2. 找出为什么没有显示闪光灯。

你可以试试这个:

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

希望对你有所帮助。

根据您提供的信息,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