相关 model 和 controller
class Info < ActiveRecord::Base
has_many :attachments, as: :attached_item, dependent: :
accepts_nested_attributes_for :attachments, allow_destroy: true, reject_if: proc { |attributes| attributes[:attachment].nil? }
end
class Attachment < ActiveRecord::Base
mount_uploader :attachment, AttachmentUploader
# Associations
belongs_to :attached_item, polymorphic: true
# Validations
#validates_presence_of :attachment
validates_integrity_of :attachment
# Callbacks
before_save :update_attachment_attributes
# Delegate
delegate :url, :size, :path, to: :attachment
# Virtual attributes
alias_attribute :filename, :original_filename
private
def update_attachment_attributes
if attachment.present? && attachment_changed?
self.original_filename = attachment.file.original_filename
self.content_type = attachment.file.content_type
end
end
end
class **InfoController** < ApplicationController
def create
info = Info.new(info_params)
attachs = []
# **这里没有执行, 我在控制台,取值是空,单独用attachmentController上传却成功了,且能正常显示**
info.attachments.each do |a|
attachs << a.attachment.url
puts "url ----------------------"
puts aattachment.url
end
if info.save
render json: {flag: 1, msg: "file upload success!",attachment_url: attachs}
else
render json: {flag: 0, msg: "#{info.errors}, file upload failed,please upload again."}
end
end
private
def info_params
params.permit(:title, :content,attachments_attributes: [:attachment, :attachment_cache])
end
end
#这个上传正常显示
class ** AttachmentController** < ApplicationController
#skip_before_action :require_logi
def create
a = Attachment.create attachment_params
if a
render json: {flag: 1, msg: a.url}
else
render json: {flag: 0, msg: 'fail'}
end
end
private
def attachment_params
params.permit(:attachment)
end
end
class AttachmentController < ApplicationController
#skip_before_action :require_login
def create
a = Attachment.create attachment_params
if a
render json: {flag: 1, msg: a.url}
else
render json: {flag: 0, msg: 'fail'}
end
end
private
def attachment_params
params.permit(:attachment)
end
end
谢谢