Ruby on rails Simple_form required字段不起作用-Ruby on Rails

Ruby on rails Simple_form required字段不起作用-Ruby on Rails,ruby-on-rails,ruby,ruby-on-rails-4,simple-form,Ruby On Rails,Ruby,Ruby On Rails 4,Simple Form,我在RoR应用程序中有一个提交表单,使用简单的表单构建。当字段为空时,应用程序仍会进入下一步,而不会提示错误或警告。默认情况下,这些字段应该是必需的:true;但即使是手动编写也不起作用 该应用程序有3个步骤:新建帖子(新建视图)->预览(创建视图)->发布 我的控制器和视图摘录会更清楚: def new @post= Post.new end def create @post = Post.new(params.require(:post).permit(:title, :c

我在RoR应用程序中有一个提交表单,使用简单的表单构建。当字段为空时,应用程序仍会进入下一步,而不会提示错误或警告。默认情况下,这些字段应该是
必需的:true
;但即使是手动编写也不起作用

该应用程序有3个步骤:新建帖子(新建视图)->预览(创建视图)->发布

我的控制器和视图摘录会更清楚:

def new
    @post= Post.new
end

def create
    @post = Post.new(params.require(:post).permit(:title, :category_id))

    if params[:previewButt] == "Continue to Preview your Post"
      render :create
    elsif params[:createButt] == "OK! Continue to Post it"
      if @post.save!
      redirect_to root_path
      else
      render :new
      end 
    elsif params[:backButt] == "Make changes"
      render :new
    end
  end
我的视图(摘录):


它将进入创建视图,因为您没有告诉它任何不同

@post=post.new(参数require(:post).permit(:title,:category_id))

使用表单中给定的空参数创建
Post
的新实例。新调用在验证方面没有任何作用。你想要的是:

@post = Post.new(params.require(:post).permit(:title, :category_id))

if @post.valid? && params[:previewButt] == "Continue to Preview your Post"
....

simple_form initialiser中有一个设置,用于激活客户端验证。不管客户端验证如何,您也必须保留服务器端验证(您当前正在做的事情)。要使用simple_表单实现客户端验证,请执行以下操作:

config/initializers/simple_form.rb

<%= simple_form_for @post do |form| %>
<%= form.hidden_field :title, {:value => @post.title} %>
<%= form.hidden_field :category_id, {:value => @post.category_id} %>
<% end %>
class Post < ActiveRecord::Base
    belongs_to :category
    validates :title, presence: true
    validates :category_id, presence: true
end
      def create
        @post = Post.new(params.require(:post).permit(:title, :category_id))

        if params[:previewButt] == "Continue to Preview your Post"
           if @post.valid? 
              render :create
           else
              render :new 
        elsif params[:createButt] == "OK! Continue to Post it"
          if @post.save!
          redirect_to root_path
          else
          render :new
          end 
        elsif params[:backButt] == "Make changes"
          render :new
        end
      end
@post = Post.new(params.require(:post).permit(:title, :category_id))

if @post.valid? && params[:previewButt] == "Continue to Preview your Post"
....
config.browser_validations = true