验证存在不起作用

时间:2016-06-18 16:18:16

标签: ruby-on-rails validation simple-form

所以我有一个表单,用户可以上传图像并为其输入标题,这两个字段都是必需的。以下是相关文件中的代码:

post.rb

class Post < ActiveRecord::Base

  validates :image, presence: true
  validates :caption, presence: true

  has_attached_file :image, styles: { :medium => "640x" }
  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/

end

posts_controller.rb

def new
  @post = Post.new
end

def create
  if @post = Post.create(post_params)
    flash[:success] = "Your post has been created!"
    redirect_to posts_path
  else
    flash.now[:alert] = "Your new post couldn't be created! Please check the form."
    render :new
  end
end

_form.html.haml

.form-wrapper
  = simple_form_for @post, html: { class: 'form-horizontal', multipart: true } do |f|
    .form-group
      = f.input :image, required: true
    .form-group.text-center
      = f.input :caption, required: true
    .form-group.text-center
      = f.button :submit, class: 'btn-success'

尽管同时拥有validates presence: truerequire: true,但表单似乎并未验证图片或标题的存在。我看到两个字段旁边的星号,表示它们是必需的,但出于某种原因,如果我将任何em(或两者)留空,表单会重定向到posts_path并闪烁“你的帖子有被创造了!“顺便说一下,帖子不会被创建。这只是重定向而已经搞砸了。提前谢谢!

0 个答案:

没有答案