2

考虑一个博客应用程序,其中包含一个用于创建新帖子的表单。有两个按钮,“保存”,“保存并继续编辑”,保存后会相应地重定向用户。

这是代码:

def create
  @post = current_user.posts.build(params[:post])
  if @post.save
    if params[:commit] == "Create & continue editing"
      redirect_to edit_admin_post_path(@post), :notice => "Post record has been created"
    else
      redirect_to admin_posts_path, :notice => "Post record has been created"
    end
  else
    flash.now[:error] = "Post record has some validation errors"
    render :new
  end
end

这是做到这一点的最好方法,还是有其他方法可以重构它?

4

1 回答 1

3

也许是这样的:

鉴于:

<%= submit_tag 'Save', name: 'save' %>
<%= submit_tag 'Save and continue editing', name: 'save_and_edit' %>

在控制器中:

def create
  @post = current_user.posts.build(params[:post])
  if @post.save
    redirect_to(params[:commit] == 'save' ? admin_posts_path : edit_admin_post_path(@post), notice: "Post record has been created")
  else
    flash.now[:error] = "Post record has some validation errors"
    render :new
  end
end
于 2013-06-11T08:12:19.423 回答