has_one 无法上传附件

can't upload attachement with has_one

嗨,我遇到了 papercliphas_one 关联的问题:

track.rb

class Track < ActiveRecord::Base
  belongs_to :lesson

  has_attached_file :track,
                :path => ":rails_root/public/system/lessons/tracks//:id/:basename.:extension",
                :url => "/system/lessons/tracks/:id/:basename.:extension"
  validates :track,
        attachment_content_type: { content_type: [ 'audio/mpeg', 'audio/x-mpeg',
                                                   'audio/mp3', 'audio/x-mp3',
                                                   'audio/mpeg3', 'audio/x-mpeg3',
                                                   'audio/mpg', 'audio/x-mpg',
                                                   'audio/x-mpegaudio' ]}
end

lesson.rb

class Lesson < ActiveRecord::Base
  has_one :track , dependent: :destroy
  accepts_nested_attributes_for :track, :allow_destroy => true
end

lessons_controller

def new
  @lesson = Lesson.new
  @levels = Level.all.map{|c| [ c.name, c.id ] }
end

def lesson_params
  params.require(:lesson).permit(:title, :content, :level_id, :video_id,  :bpm,
                                 :artist, track_attributes: [:id, :track])
end

_form.html.slim

= form_for @lesson, :class => 'form-horizontal', html: { multipart: true } do |f|
  = f.fields_for :track, :html => {:multipart => true} do |t|
      = t.file_field :track

migration track

class CreateTracks < ActiveRecord::Migration
  def change
    create_table :tracks do |t|
      t.timestamps null: false
      t.has_attached_file :track
    end
  end
end

migration lessons

class CreateLessons < ActiveRecord::Migration
  def change
    create_table :lessons do |t|

      t.timestamps null: false
      t.string :title
      t.string :artist
      t.text :content
      t.string :video_id
      t.integer :bpm
      t.references :track, index: true
      t.references :level, index: true
    end
  end
end

所以我的上传字段只有在我将表单中的 fields_for :track 替换为 fields_for :tracks 时才会显示,但随后出现错误:unpermitted parameter.

关于问题可能来自何处的任何想法?

可以,但您需要按如下方式构建嵌套对象:

@lesson.build_track

将以上行添加到您的控制器中。它将以给定的形式显示轨道的文件输入字段。