Railsにお詳しい方のお知恵をお借しください……
親テーブル(workitems)の編集フォームからアップロードされたファイルを、
子テーブル(destination)へ保存しようとしているのですが、なかなか上手く行きません。
アップロードされるファイルはCSV(text/csv)のみです。
paperclipが有効という情報を見つけ、あちこち参考にしつつ試したのですが、
「contenttypeが不正」というエラーが回避できず……
仕方なく自力でbinary型の列へ保存する方法を行おうとしてるのですが、
こちらでも躓いてしまい途方に暮れております。
Model(~/app/models/workitem.rb , ~/app/models/destination.rb)
lang
1class Workitem < ActiveRecord::Base 2 # rails g scaffold workitem name:string 3 has_one :destination, :dependent => :destroy 4 accepts_nested_attributes_for :destination 5end 6 7class Destination < ActiveRecord::Base 8 # rails g model destination name:string workitem_id:integer upload_file:binary 9 belongs_to :workitem 10end
View(~/app/views/workitems/_form.html.erb)
lang
1<%= form_for @workitem, multipart: true do |f| %> 2 <%= f.fields_for @workitem.destination do |dest_f| %> 3 <%= dest_f.file_field :upload_file %> 4 <% end %> 5<% end %>
Controller(~/app/controllers/workitems_controller.rb)
lang
1class WorkitemsController < ApplicationController 2 def new 3 @workitem = Workitem.new 4 @workitem.build_destination 5 end 6 7 def create 8 # あれこれ試してみて自力でパラメータを作ればどうにかなるかと以下のコードを書きました 9 10 # workitem_paramsを退避。ファイルがアップロードされなければ 11 # こいつがこのまま使用されるので問題ないはず 12 temp_workitem_params = workitem_params 13 destination_attributes = workitem_params[:destination_attributes] 14 upload_file = destination_attributes[:upload_file] 15 # => ActionDispath::Http::UploadedFile 16 17 if upload_file != nil 18 # ファイルがアップロードされてれば 19 if @workitem.destination != nil 20 # 既存のアップロードファイルがあれば消す 21 @workitem.destination.destroy 22 end 23 24 # アップロードされたファイルの情報をworkitem_param[:destination_attributes]に仕込む 25 content = {} 26 content[:filename] = upload_file.original_filename 27 content[:upload_file] = upload_file.read 28 29 temp_workitem_params.delete('destination_attributes') 30 temp_workitem_params['destination_attributes'] = content 31 end 32 33 @workitem = Workitem.new(temp_workitem_params) 34 respond_to do |format| 35 if @workitem.save 36 # この中身はそのまま 37 end 38 end 39 end 40 41 def update 42 # create と同じく、workitem_paramsからDispatch::Http::UploadedFileの情報を展開し、 43 # destination_attributesの中身を差し替えて@workitem.updateを行っています 44 end 45 46 private 47 def workitem_params 48 params.require(:workitem).permit(:name, destination_attributes: [ :upload_file, :filename, :workitem_id ]) 49 end 50end
上記のような構成にてデータの更新を行おうとすると、
ActiveModel::ForbiddenAttributesError という例外が発生してしまいます。
ストロングパラメータはテーブルのものと同じにしてあるのですが、
どこが原因なのか皆目検討もつかず……
サーバ環境は
- CentOS 6.6
- ruby 2.0.0p645
- Rails 4.2.1
となっております。
workitemが登録・更新されるタイミングでファイルのアップロードも行いたいため
色々と調べてはみたのですが、これ以上はどうしもうよなく……
不足している情報があれば分かる範囲でお出ししますので、よろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。