现在我正在尝试在注册时为用户下载随机头像。
所以我得到了 Mechanize 并在研究后做到这一点。
class RegistrationsController < Devise::RegistrationsController
def new
super
end
def create
agent = Mechanize.new
agent.pluggable_parser.default = Mechanize::Download
f = agent.get('http://avatar.3sd.me/100')
f.save('public/images/avatar/it_should_be_user_id.png')
super
end
def update
super
end
end
但是我不知道如何根据用户ID以特定名称保存文件,该怎么做?
最佳答案
建议你先在create
中调用super方法,因此设计 Controller 的默认设置发生在您的代码执行之前。
内RegistrationsController
您可以使用变量/方法访问当前用户的类 resource
(而不是像 current_user
之类的东西)。所以你的代码看起来像这样:
class RegistrationsController < Devise::RegistrationsController
def new
super
end
def create
super
agent = Mechanize.new
agent.pluggable_parser.default = Mechanize::Download
f = agent.get('http://avatar.3sd.me/100')
f.save("public/images/avatar/#{resource.id}.png")
end
def update
super
end
end
关于ruby-on-rails - rails : Download by Mechanize custom filename,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24327617/