现在我正在尝试下载一个随机头像的用户,而注册。所以我找了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,这样在你的代码执行之前,控制器的默认设置就会发生。
在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