我正在使用activeadmin,如果在目录中找到,则以下代码应该为卡片分配照片。
卡片型号不接受新照片,它从不指定新值,保存返回true。
更新:问题是该属性上安装了载波上传器。注释掉它使它工作,但它确实不是一个可接受的解决方案,因为这是一个必须重复进行的动作...是否有办法卸载上传器或直接设置属性值与上传器挂载?我似乎无法在网上找到任何内容......
更新:载入wavewave时,即使ActiveRecord::Base.connection.execute("update cards set photo='#{f.to_s}' where id=#{card.id};")
也失败了...我猜它已被接管了
更新:事实证明我的问题是重复的 Manually updating attributes mounted by Carrierwave Uploader
来自日志:
Card Load (0.5ms) SELECT `cards`.* FROM `cards` WHERE `cards`.`gatherer_id` = 244675 LIMIT 1
(0.2ms) BEGIN
Card Load (0.4ms) SELECT `cards`.* FROM `cards` WHERE `cards`.`id` = 1377 LIMIT 1
SQL (0.5ms) UPDATE `cards` SET `photo` = NULL, `updated_at` = '2013-11-22 11:20:44' WHERE `cards`.`id` = 1377
(4.1ms) COMMIT
在未安装carrierwave并且属性的值更新后很好,之后,当再次安装carrierwave时,它会根据上传器store_dir正常返回文件位置。唯一的问题是我无法在安装上传器时设置值。作为最后的手段,我会用普通的旧sql来做,我只是不喜欢这个想法。
activeadmin action:
ActiveAdmin.register_page 'Import FTP photos' do
menu label: 'Import FTP photos', parent: 'Cards'
#action_item do
# link_to 'View Site', '/'
#end
content do
require 'fileutils'
para 'Importing photos...'
from_dir = 'var/uploads/card_photos'
uploads_dir = 'public/uploads/card/photo/'
Dir.foreach(from_dir) do |f|
next if f == '.' or f == '..'
from_file = from_dir + '/' + f.to_s
id = f.gsub(/\.\w+$/, '')
card = Card.find_by_gatherer_id(id)
if card
to_dir = uploads_dir+card.id.to_s
to_file = to_dir + '/' + f.to_s
Dir.mkdir(to_dir) if Dir.new(to_dir).nil?
FileUtils.remove(to_file) if FileTest.exists?(to_file)
FileUtils.mv(from_file, to_file)
card.photo = f.to_s
card.save
end
end
end
end
卡片型号
class Card < ActiveRecord::Base
mount_uploader :photo, PhotoUploader
belongs_to :card_set
belongs_to :card_artist
def to_s
caption
end
private
def card_params
params.permit!
end
end