您好paperclip
与has_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
。
关于问题可能来自哪里的任何想法?
答案 0 :(得分:0)
是的,它可以工作,但您需要按如下方式构建嵌套对象:
@lesson.build_track
将以上行添加到您的控制器中。它将以给定的形式显示轨道的文件输入字段。