2014-06-20 35 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