0

是否可以在没有新方法的情况下进行模型错误报告?据我了解,当您要报告错误时,您将创建以下控制器代码:

 def new
    @product = Product.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @product }
    end
  end

  def create
    @product = Product.new(params[:product])

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
        format.json { render json: @product, status: :created, location: @product }
      else
        format.html { render action: "new" }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

然后您将创建一个包含以下代码的表单:

<% if @product.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>

      <ul>
      <% @product.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

但是,您能否仅在控制器中使用“创建”方法来复制此技术?例如,使用 form_tag 将数据传递给“create”方法。也许是这样的:

'post', :class => 'form-horizo​​ntal', :style => 'text-align:center') 做 %>
            <% unless @product.blank? %>
              <% if @product.errors.any? %>
                <div id="error_explanation">
                  <h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>

                  <ul>
                  <% @product.errors.full_messages.each do |msg| %>
                    <li><%= msg %></li>
                  <% end %>
                  </ul>
                </div>
              <% end %>
            <% end %>

               <%= text_area_tag :content, '', :placeholder => 'Ask your classmates anything...' %>
               <%= hidden_field_tag :user_id, current_user.id %>
               <%= submit_tag 'Post', :class => "btn btn-medium btn-primary post-room-button"  %>
            <% end %>

I have been trying to do this, but I cannot find a way to get it to work. Whenever I submit the form that fails one of the validations in my model, the page simply redirects to my 'else' path in my respond_to function in my create controller.

4

1 回答 1

0

You can remove the compete new method from your controller but not the new view present in the views file.

When you say render action: "new" it renders the new.html.erb file present in the views folder of your app and when you say redirect_to action: "new" it will call the new action of the controller and will perform the operations present in the new action and then render the new.html.erb.

You cannot render the create action as it does not contain any view file and create action as per REST is supported by POST request and not GET request

于 2012-08-13T11:48:59.557 回答