I have a user view where I allow a user to upload his own image or allow him to import image from his LinkedIn profile. My LinkedIn OAuth works fine and returns the url of the image located on linkedin servers. I have a picture_from_url method in my User model which is called by UsersController in it's update method. I set the url to a sessions variable and then send that to the model method in the controller. This ,however, is not updating the image for the user. I have the papertrail gem setup so he can use the image from his computer and change his profile picture just fine.
My Model method
def picture_from_url(url)
encoded_url = URI.encode(url.to_s)
avatar= URI.parse(encoded_url)
end
My Controller Call
def update
@user = User.find(params[:id])
@user.picture_from_url(session[:linkedin_picture])
respond_to do |format|
if can?(current_user, @user)
if @user.update_attributes(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render_success @user }
else
format.html { render action: 'edit' }
format.json { render_error @user }
end
else
format.html { render action: 'edit', status: :unprocessable_entity }
format.json { render_error @user }
end
end
end
You're not actually saving it (as you said).
You supply your picture_from_url
method with a URL, encode and parse it. The last thing you do with it is set it to avatar
. I'm guessing that's an attribute on your User
model. You're not saving it though.
The following line in your controller doesn't save it either:
@user.update_attributes(user_params)
The above line is updating your @user
record with the specified user_params
and the URL isn't specified in it.
So, you either have to save your @user
record when you call the picture_from_url
method like this:
def picture_from_url(url)
encoded_url = URI.encode(url.to_s)
update_attributes avatar: URI.parse(encoded_url)
end
Or you can add the formatted URL (which you can retrieve from the picture_from_url
method) to the user_params
hash which is than saved when update_attributes
is called in your controller, like this:
def picture_from_url(url)
encoded_url = URI.encode(url.to_s)
URI.parse encoded_url
end
Change the picture_from_url
method to the above in your User
model (technically you don't have to do this, but it is probably more readable) and your update
action to the following:
def update
@user = User.find(params[:id])
user_params.merge! avatar: @user.picture_from_url(session[:linkedin_picture])
...
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.