我正在尝试从我的模型中强制使用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
的各种迭代但无济于事。
有两个问题。
答案 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