Simple_form必填字段不起作用 – Ruby on Rails

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

该应用程序有3个步骤:NewPost(新视图) – >预览(创建视图) – >发布。

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

 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 

我的观点(摘录):

    "selectable" ) %>   

我的创建视图(提取):

   @post.title} %>  @post.category_id} %>  

请注意,问题不在保存时,模型定义可以正常工作,问题仅在于simple_form。

 class Post < ActiveRecord::Base belongs_to :category validates :title, presence: true validates :category_id, presence: true end 

解决方案感谢DickieBoy提示:

将控制器更改为:

  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))

使用表单中给出的参数为空创建Post的新实例。 新的调用在validation方面没有任何作用。 你想要的东西:

 @post = Post.new(params.require(:post).permit(:title, :category_id)) if @post.valid? && params[:previewButt] == "Continue to Preview your Post" .... 

simple_form初始化程序中有一个设置可激活客户端validation。 无论客户端validation如何,您都必须保持服务器端validation(您当前正在进行的操作)。 要使用simple_form实现客户端validation,请执行以下操作:

配置/初始化/ simple_form.rb

 config.browser_validations = true