【问题标题】:Rails 4 Multiple Pictures with PaperclipRails 4 带回形针的多张图片
【发布时间】:2014-10-10 18:45:16
【问题描述】:

我正在尝试使用 Rails 4 中的 Paperclip gem 将多张图片添加到项目中。

图片没有上传到数据库。使用 MySQL。

我不断收到此错误:

2 个错误禁止保存此论坛主题:

照片照片内容类型无效

照片照片无效

请求参数:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"zoMHhVTJOy0/VVGNCcVrTaFwmSRvYoonQEtc+TAqwCM=",  "project"=>{"photos_attributes"=>{"0"=>{"photo"=>#<ActionDispatch::Http::UploadedFile:0x007f98f0d4b468 @tempfile=#<Tempfile:/var/folders/gp/jz4_vlrs2l96__g4jrnsc3y40000gn/T/RackMultipart20141010-4840-1gtf4ao>, @original_filename="glyphicons-halflings-white.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"project[photos_attributes][0][photo]\"; filename=\"glyphicons-halflings-white.png\"\r\nContent-Type: image/png\r\n">}}, "title"=>"sadfsadfdsa", "description"=>"sdfsdafsdf"}, "commit"=>"Create Project"}

我在下面添加了必要的文件。

** 新建项目 Erb/HTML 文件**

<% provide(:title, "New Project") %>

<div class="page-header">
 <h2>New Project</h2>
</div>

<%= form_for @project, :html => { :multipart => true } do |f| %>
 <% if @project.errors.any? %>
 <div id="error_explanation">
 <h2><%= pluralize(@project.errors.count, "error") %> prohibited this forum topic from being saved:   </h2>
  <ul>
   <% @project.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
   <% end %>
  </ul>
</div>
  <%= f.fields_for :photos do |f| %>
    <div class="form-group">
     <%= f.file_field :photo , class: 'form-group' %>
  </div>
<% end %>

<div class="form-group">
 <%= f.text_area :title, class: 'form-control input-lg', placeholder: 'Topic Title' %>
</div>
<div class="form-group">
 <%= f.text_area :description, rows: 4, class: 'form-control', placeholder: 'Topic Description' %>
</div>

<div class="actions">
 <%= f.submit class: 'btn btn-success'%>
</div>
<% end %>

项目负责人:

class ProjectsController < ApplicationController
  before_filter :authenticate_user!, except: [:show, :index]
  before_filter :set_project, except: [:index, :new, :create]

def index
 @projects = Project.find(:all)
end

def show
end

def new
 @project = Project.new
 3.times {@project.photos.build}
end

def create
 @project = current_user.projects.build(project_params)
  if @project.save
    flash[:success] = "Project Created!"
    redirect_to @project
  else
    render :new
  end
end

def edit
 3.times {@project.photos.build}
end

def update
 if @project.update_attributes(project_params)
  flash[:notice] = "Successfully updated your project."
  redirect_to @project
 else
   render :edit
  end
end

def destroy  
end

private

# Never trust parameters from the scary internet, only allow the white list through.
def project_params
 params.require(:project).permit(:title, :description, photos: [], photos_attributes:[:photo, :id])
end

def set_project
 @project = Project.find(params[:id])
end

项目模型:

  class Project < ActiveRecord::Base
    belongs_to :user, counter_cache: true
    has_many :photos

  default_scope -> { order('created_at DESC') }
   validates :title, presence: true, length: {maximum: 50}
   validates :description, presence: true, length: { maximum: 1000 }
   validates :user_id, presence: true

  accepts_nested_attributes_for :photos, :reject_if => lambda { |t| t[:photo].nil? }

  def photos=(files = [])
   files.each{|f| (@images ||= []) << photos.create(image: f) }
  end
 end

照片模特:

 class Photo < ActiveRecord::Base
 belongs_to :user, counter_cache: true
 belongs_to :project, counter_cache: true

 has_attached_file :photo, :styles => { :small => "150x150>", :large => "320x240>" }
 validates_attachment_presence :photo
 validates_attachment_size :photo, :less_than => 5.megabytes
 validates_attachment :photo, content_type: { content_type: ["photo/jpg", "photo/jpeg", "photo/png", "photo/gif"] }
 end

照片迁移:

class AddPhotosToPhotos < ActiveRecord::Migration
 def self.up
  add_column :photos, :photo_file_name,    :string
  add_column :photos, :photo_content_type, :string
  add_column :photos, :photo_file_size,    :integer
  add_column :photos, :photo_updated_at,   :datetime
 end

def self.down
 remove_column :photos, :photo_file_name
 remove_column :photos, :photo_content_type
 remove_column :photos, :photo_file_size
 remove_column :photos, :photo_updated_at
 end
end

用于索引的照片迁移

class CreatePhotos < ActiveRecord::Migration
 def change
  create_table :photos do |t|
    t.integer :user_id
    t.integer :project_id
    t.timestamps
   end
  end
 end

Development.rb

Paperclip.options[:command_path] = "/usr/local/bin/"

【问题讨论】:

    标签: image ruby-on-rails-4 model paperclip


    【解决方案1】:

    首先,内容类型错误 - 将您的 validates_attachment 更改为图像类型:

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

    至于另一个错误,它看起来像是在这里出现的:

      <%= f.fields_for :photos do |f| %>
        <div class="form-group">
          <%= f.file_field :photo , class: 'form-group' %>
        </div>
      <% end %>
    

    复数 fields_for 中的单数照片可能存在问题。诚然,我没有检查文档。如果没有,将需要有关错误的更多详细信息进行故障排除。在 create 操作中调用 project_params 会发生什么?

    【讨论】:

    • 修复内容验证将解决其他错误的好机会,让我们希望。
    • 感谢您的回答!将 fields_for 更改为“照片”和 validates_attachment 无效。我相信内容类型更改为“图像”让我走上了正轨,但问题出在代码的其他地方。
    猜你喜欢
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 1970-01-01
    • 2016-09-01
    相关资源
    最近更新 更多