我是否需要与向用户推送消息的方式保持一致?

时间:2016-04-25 18:32:37

标签: ruby-on-rails

我现在已经完成了一些教程,我似乎有各种向用户显示消息的方法。

例如,在控制器中我有这个动作:

  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。

如果我以不同的格式推送这些或者它们都一样吗?我错过了最佳做法吗?

1 个答案:

答案 0 :(得分:0)

当您在flash方法中指定noticeredirect_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中提到了它。