So I have a web app that let users sign up with twitter. So there profile pictures & name are associated to their users accounts.
They can also crate profiles (another model), in these profiles they can fill in name, photos and more.
I succeeded to pre-fill the name field from users name on twitter like this:
In my profiles_controller.rb:
def new
@profile = Profile.new :twitter => current_user.name
end
What I would like to do is to import users images (imported from twitter) inside this form.
So i tried:
def new
@pin = Pin.new :twitter => current_user.name, :image => current_user.image
end
But all I get in my form is a broken image preview.
As I am using paperclip to upload images on my app, is there a way to transfer a twitter image to paperclip inside a form ? I am not sure how to do it. Any helps would be lovely appreciated.
Edit:
Here is the part of my user model where I retrieve user image from twitter Oauth: User.rb:
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.nickname
user.image = auth["info"]["image"].sub("_normal", "")
end
end
I call the user image like this in my views:
<%= image_tag user.image %>
But the questions is how could I upload the User image to the profile form:
I have: app/profile/views/_form.html.erb:
<%= f.file_field :image %>
How could I trick this f.file_field to automatically import users.image if he doesn't want to uplaod a different profile picture form its twitter profile ?
You don't really need to do this. Twitter provides a link to the profile image, if you check the documentation...
"profile_image_url":
"http://a0.twimg.com/profile_images/2284174872/7df3h38zabcvjylnyfe3_normal.png"
Store the URL in the user record and Use the url to display the image if you have no user-uploaded image available.
You can refresh it to the latest URL on every oAuth log in, and that way you always show the user's latest Twitter profile image.
EDIT
So, create a field in your User model to store the twitter image url...
rails g migration AddTwitterImageToUser twitter_image.string
rake db:migrate
Populate the field when you log in via Twitter...
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.nickname
user.twitter_image = auth.info.profile_image_url
end
end
Then to display...
<% if user && user.twitter_image.present? %>
<img src="<%= user.twitter_image %>" >
<% end %>
I'm not personally aware of "nickname" being an available field in the Twitter API so I'm not positive about the contents of the info
attribute in the auth
object... you may want to confirm image url is available by inpecting the object... dump it to the logger or use pry
.