ruby-on-rails - Paperclip::Errors::MissingRequiredValidatorError 与 Rails 4

标签 ruby-on-rails ruby ruby-on-rails-4 paperclip

当我尝试通过我的 Rails 博客应用程序使用回形针上传时,我遇到了这个错误。 当它说“MissingRequiredValidatorError”时不确定它指的是什么 我认为通过更新 post_params 并给它 :image 就可以了,因为创建和更新都使用 post_params

Paperclip::Errors::MissingRequiredValidatorError in PostsController#create
Paperclip::Errors::MissingRequiredValidatorError

Extracted source (around line #30):

def create
  @post = Post.new(post_params)

这是我的 posts_controller.rb

def update
  @post = Post.find(params[:id])

  if @post.update(post_params)
    redirect_to action: :show, id: @post.id
  else
    render 'edit'
  end
end

def new
  @post = Post.new
end

def create
  @post = Post.new(post_params)

  if @post.save
    redirect_to action: :show, id: @post.id
  else
    render 'new'
  end
end
#...

private

def post_params
  params.require(:post).permit(:title, :text, :image)
end    

这是我的帖子助手

module PostsHelper
  def post_params
    params.require(:post).permit(:title, :body, :tag_list, :image)
  end
end

如果我可以补充额外的 Material 来帮助你帮助我,请告诉我。

最佳答案

Paperclip 版本 4.0 开始,所有附件都需要包括content_type 验证file_name 验证,或者显式 声明他们两者都不会。

如果您不执行任何操作,Paperclip 将引发 Paperclip::Errors::MissingRequiredValidatorError 错误。

在您的情况下,您可以将以下任何行添加到您的Post 模型, 指定has_attached_file :image

选项 1:验证内容类型

validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]

-或-另一种方式

validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }

-或-另一种方式

是使用regex 来验证内容类型。

例如:要验证所有图像格式,可以指定正则表达式,如下所示

@LucasCaton's answer

选项 2:验证文件名

validates_attachment_file_name :image, :matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]

选项 3:不验证

如果出于某些疯狂的原因(可能是有效但我现在想不出一个),您不想添加任何content_type 验证并允许人们欺骗 Content-Types 并将您不期望的数据接收到您的服务器上,然后添加以下内容:

do_not_validate_attachment_file_type :image

注意:

在上面的 content_type/matches 选项中根据您的要求指定 MIME 类型。我刚刚为您提供了一些图像 MIME 类型开始。

引用:

引用 Paperclip: Security Validations ,如果还需要验证。 :)

您可能还必须处理此处解释的欺骗验证 https://stackoverflow.com/a/23846121

关于ruby-on-rails - Paperclip::Errors::MissingRequiredValidatorError 与 Rails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21897725/

相关文章:

ruby-on-rails - Rails 中类变量的线程安全性 - 这行得通吗?

ruby - hpricot-UTF-8 中的无效字节序列

ruby-on-rails - 自动创建 rails locale yaml 文件?

ruby-on-rails - 未定义方法 `<<' 为 nil :NilClass got this error while merging instance variables

javascript - 用coffeescript中的图像替换文本

ruby - 仅从字符串中删除 anchor 标记

ruby-on-rails - 如何在 Rails 应用程序中对 Gems 加载时间进行基准测试

ruby-on-rails - 地理编码器位置查找

ruby-on-rails - 如何对我的 Rails 应用程序的 CRUD 部分进行 DRY?

ruby-on-rails - Rails accepts_nested_attributes_for with _destroy 可以跳过存在验证