我试图使用回形针将Files
附加到Log
上,使用带有简单表单的嵌套表单。当文件是模型的属性时,我能够附加一个文件,但我需要能够将多个文件关联到日志(一对多),这就是我现在有两个模型的原因。我得到了下面的错误,但我不知道我遗漏了什么。
没有为[#,@original_filename="1314e40ac73ab769790aea881730e12f.jpg",@content_type=“@content_type=/jpeg”,@headers=“内容-处理:表单数据;name=\"logdocuments_attributesattachment\";filename=\"1314e40ac73ab769790aea881730e12f.jpg\"\r\nContent-Type:@content_type=/jpeg\r\n”“)找到处理程序 , filename=\"fsdfsdafsad-large.png\"\r\nContent-Type:“@original_filename=/png”,@content_type=“@content_type=/png”,@headers=“内容-处理:表单数据”;name=\"logdocuments_attributesattachment\";@content_type=图像/png\r\n“>]
Document
模型:
class Document < ApplicationRecord
default_scope { order(created_at: :desc) }
belongs_to :log
has_attached_file :attachment
validates :log, presence: true
validates_attachment_content_type :attachment, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
Log
模型:
class Log < ApplicationRecord
default_scope { order(created_at: :desc) }
belongs_to :user
belongs_to :server
has_many :documents, dependent: :destroy
accepts_nested_attributes_for :documents
do_not_validate_attachment_file_type :documents
end
Log
控制器:
# GET /logs/new
def new
@log = Log.new
@log.documents.build
end
# POST /logs
# POST /logs.json
def create
@log = Log.new(log_params)
if params[:documents_attributes]
params[:documents_attributes].each do |doc|
@log.documents.create(attachment: doc)
end
end
#binding.pry
respond_to do |format|
if @log.save
binding.pry
format.html { redirect_to log_path(@log), notice: 'Log was successfully created.' }
format.json { render :show, status: :created, location: @log }
else
format.html { render :new }
format.json { render json: @log.errors, status: :unprocessable_entity }
end
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def log_params
params.require(:log).permit(:user_id, documents_attributes: [:log_id, attachment: []])
end
Log
窗体视图
<%= simple_form_for @log, html: { class: 'form-horizontal', enctype: 'multipart/form-data', local: true, multipart: true } do |f| %>
<%= f.simple_fields_for :documents, @log.documents do |ff| %>
<%= ff.input :attachment, as: :file, input_html: { multiple: true } %>
<% end %>
<% end %>
更新:错误由@log = Log.new(log_params)
在my Log
控制器的create
操作中触发。
发布于 2018-02-24 11:01:23
回形针设计为每个“列”接受一个文件。不能在Document
的附件中添加多个文件。解决方案要么是找到另一个支持多个文件的gem (载波将是最流行的),要么创建一个新的资源(例如Attachment
),即belongs_to Document
并在那里添加has_attached_file
。
PS:您得到的错误正在发生,因为在您的log_params
中,您正在发送附件,期望它返回多个值,而回形针无法以这种方式处理附件。
https://stackoverflow.com/questions/48646222
复制相似问题