我现在已经完成了一些教程,我似乎有各种向用户显示消息的方法。
例如,在控制器中我有这个动作:
def edit
user = User.find_by(email: params[:email])
if user && !user.activated? && user.authenticated?(:activation, params[:id])
user.activate
log_in user
flash[:success] = "Account activated! Welcome to foodiker!"
redirect_to root_url
else
flash[:danger] = "Invalid activation link."
redirect_to root_url
end
end
有时在控制器中我有这个:
def create
@recipe = Recipe.new(recipe_params)
respond_to do |format|
if @recipe.save
current_user.recipes << @recipe
format.html { redirect_to myrecipes_url, notice: 'Recipe was successfully created.' }
format.json { render :show, status: :created, location: @recipe }
else
format.html { render :new }
format.json { render json: @recipe.errors, status: :unprocessable_entity }
end
end
end
我还阅读了诸如响应者gem之类的内容,并使用了respond_with而不是respond_to。
如果我以不同的格式推送这些或者它们都一样吗?我错过了最佳做法吗?
答案 0 :(得分:0)
当您在flash
方法中指定notice
或redirect_to
条消息时,它会将这些消息设置为flash
的相应密钥。
基本上,这些是等价的:
redirect_to myrecipes_url, notice: 'Recipe was successfully created.'
# The same as if you did this:
flash[:notice] = 'Recipe was successfully created.'
redirect_to myrecipes_url
方法文档的the examples section中提到了它。