每个模型使用 Paperclip 的多种不同附件类型

Multiple different attachment types per model using Paperclip

在我的 Rails 应用程序中,我有一个 Post 模型。 post 具有三种不同的附件类型,图像、歌曲或视频。

这是我的模型中的内容:

class Post < ActiveRecord::Base

    has_attached_file :image, styles: {
    large: '900x900>'
  }

  has_attached_file :song
  has_attached_file :video

  # Validate the attached image is image/jpg, image/png, etc
  validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/

  validates_attachment_content_type :song, :content_type => [ 'application/mp3','application/x-mp3', 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg', 'audio/x-mpegaudio' ],
            :message => 'Please select a .mp3 file'

  validates_attachment_content_type :video, :content_type => ['video/mp4'],
    :message => "Sorry, right now we only support MP4 video"

end

这是我控制器中的内容:

def create_new_post
    @post = Post.new
    @post.image = params[:image]
    @post.save
    redirect_to root_path
end

这是我的 posts table 架构中的内容:

t.string   "image_file_name"
t.string   "image_content_type"
t.integer  "image_file_size"
t.datetime "image_updated_at"
t.string   "song_file_name"
t.string   "song_content_type"
t.integer  "song_file_size"
t.datetime "song_updated_at"
t.string   "video_file_name"
t.string   "video_content_type"
t.integer  "video_file_size"
t.datetime "video_updated_at"

我正在使用 form_tag 创建 post。并非所有附件都需要创建 post。提交我的表单后出现此错误:

undefined method `song_content_type' for #<Post:0x007fa704a54b70>

是什么原因造成的,我怎样才能让它发挥作用?

要使 validates_attachment_content_type :song 正常工作,您需要在 Post 模型(posts table)上定义一个 song_content_type 属性。

您的 schema.rb 应该包含如下内容:

create_table "posts" do |t|
  t.string   "song_file_name"
  t.string   "song_content_type"
  t.integer  "song_file_size"
  ...
end