2014-06-20 34 views
0

现在我试图在注册时为用户下载一个随机头像。 所以我得到机械化,并在研究后做到这一点。Rails:通过机械化自定义文件名下载

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文件保存在特定的名称,该怎么办呢?

回答

1

我建议你在create方法中调用超级优先,所以在你的代码执行之前,devise控制器的默认设置发生了。

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 
+0

非常感谢, 它做的工作 – user3759996

+1

我很高兴它。你介意接受这个答案作为最好的答案吗? – gitcdn