Rails 4 - 如何在提交表单后呈现相同的视图

时间:2016-03-17 04:45:26

标签: validation ruby-on-rails-4 activerecord

如何在提交表单后呈现相同的视图?

我无法呈现自定义部分错误消息。我猜它是由于我需要渲染相同的视图但我不知道该怎么做。我尝试了所有注释的行,因为我需要

   def create
    @micropost = Micropost.find(params[:micropost_id])
    @comment = @micropost.comments.create(comment_params)
    @comment.user_id = current_user.id #or whatever is you session name
    if @comment.save
      flash[:success] = "Comment created!"
      redirect_to :back
    else
      @new_comment = @micropost.comments.new
      #flash[:danger] = "Max 140 caracteres - No puede estar en blanco!" #works but is static single comment.
      #render 'microposts/show', locals: {micropost: @micropost} # I need to define all variables to in this controller again and pass to the partial (It's not DRY) 
      #redirect_to micropost_url(@micropost)  # works but not show partial errors messages
    end
  end

路线:

  resources :microposts do
    member do
      get :likes
    end
    [:create, :destroy, :show, :index]
    resources :comments
  end

3 个答案:

答案 0 :(得分:0)

由于flash消息是简单的名称值对哈希。 我认为你应该在你的视图中给出flash消息或者像这样部分: -

<% flash.each do |key, value| %>
        <div class="alert alert-<%= key %>"><%= value %></div>
      <% end %>

您应该在控制器操作中定义Flash消息。你已经完成了。

希望它有效!

答案 1 :(得分:0)

创建

def create
    @micropost = Micropost.find(params[:micropost_id])
    @comment = @micropost.comments.create(comment_params)
    @comment.user_id = current_user.id #or whatever is you session name
    respond_to do |format|
        if @comment.save
            flash[:success] = "Comment created!"
            redirect_to :back
            format.html { redirect_to @comment, notice: 'Comment created.' }
            format.json { render :show, status: :created, location: @comment }
        else
            format.html { render :new }
            format.json { render json: @comment.errors, status: :unprocessable_entity }
            #flash[:danger] = "Max 140 caracteres - No puede estar en blanco!" #works but is static single comment.
            #render 'microposts/show', locals: {micropost: @micropost} # I need to define all variables to in this controller again and pass to the partial (It's not DRY) 
            #redirect_to micropost_url(@micropost)  # works but not show partial errors messages
        end
    end
end

答案 2 :(得分:0)

阅读我可以看到这是一个重复的custom validations errors form controller inside other parent controller rails 3.1

然而,我看到的唯一解决方案是违反DRY并定义Comment#create中父视图所需的所有变量。

这也导致a在另一个url / post /:id / comment中显示帖子页面不正确。

现在我明白为什么其他人建议不要使用嵌套资源

我无法相信对于像这样的常见问题,没有一个简单的,开箱即用的解决方案。