Ruby on rails Rails:通过Mechanize自定义文件名下载

Ruby on rails Rails:通过Mechanize自定义文件名下载,ruby-on-rails,ruby,devise,mechanize,Ruby On Rails,Ruby,Devise,Mechanize,现在我正试图在注册时为用户下载一个随机的头像。 所以我会机械化,在研究之后做这件事 class RegistrationsController < Devise::RegistrationsController def new super end def create agent = Mechanize.new agent.pluggable_parser.default = Mechanize::Download f = agent.get('http:/

现在我正试图在注册时为用户下载一个随机的头像。 所以我会机械化,在研究之后做这件事

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以特定的名称保存文件,如何做?

我建议您先在
创建方法中调用super,这样在执行代码之前,设备控制器的默认设置就会发生

RegistrationController
类中,您可以使用变量/方法
资源
访问当前用户(而不是像
当前用户
)。因此,您的代码如下所示:

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
类注册控制器
我很高兴它能做到。那么你介意接受这个最好的答案吗?