我在rails博客应用中try 使用回形针上传时遇到了这个错误.

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

Extracted source (around line #30):

def create
  @post = Post.new(post_params)

这是我的控制器.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 version 4.0开始,所有附件都需要包含content_type validationa file_name validationexplicitly状态,它们都不会有.

如果不这样做,回形针会引发Paperclip::Errors::MissingRequiredValidatorError个错误.

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

选项1:验证内容类型

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

-OR- another way

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

-OR- yet another way

使用regex来验证内容类型.

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

100

选项2:验证文件名

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

选项3:不验证

如果你不想在服务器上添加content_type种类型的数据,那么我认为你现在不能添加content_type种类型的数据,但我不想在服务器上添加content_type种类型的数据:

do_not_validate_attachment_file_type :image

Note:

Specify the MIME types as per your requirement within 100/ 101 options above.我刚刚给了你们一些图片MIME类型作为开始.

Reference:

如果仍然需要验证,请参阅100.:)

您可能还需要处理此处解释的欺骗验证

Ruby-on-rails相关问答推荐

在数组中定位不匹配的索引

Sidekiq with Rails - 控制台与 rake 任务中的不同 Sidekiq 实例

一对多关联 counter_cache 在 Rails 中无法正确重新加载

Rails 创建自定义函数/方法以及存储位置

如何使用 activerecord activerecord-session_store 在 Rails 应用程序中使用 cookie 值在数据库中查找会话记录

在 Datatable Ajax 调用中通过 Ajax 更新 div

Rails 100% 新手问题 - send() 方法

如何使用 RSpec 和 Devise/CanCan 进行集成测试?

如何在 Ruby on Rails 中创建一个锚点并重定向到这个特定的锚点

rails 3:将链接显示为按钮?

如何在 rails 中指定和验证枚举?

如何从 Rails 路由中删除控制器名称?

使用devise gem点击确认链接后避免登录?

Rails Mailer Net::OpenTimeout: execution expired 仅在生产服务器上出现异常

Rails:文件路径

Rails 在关联模型中排序

mongoid 中 embeds_many 和 has_many 的区别

如何在 Ruby 中创建一个新的 Date 实例

如何在 Rails 4 中测试控制器关注点

rails 3,如何在 Settings.yml 文件中使用 ENV 配置变量?