Heroku + Rails 4 + Paperclip with AWS S3的URL无法正常工作

3

目前,我遇到了一个问题,无法获取个人资料页面上头像和个人资料封面图片的URL。

有趣的是,如果我使用以下代码,则可以显示:

current_user.avatar.url(:thumb)

# it will not show if I use:
@user.avatar.url(:thumb)

# production.rb paperclip config
config.paperclip_defaults = {
:url => ":s3_domain_url",
:path => "/:class/:attachment/:id/:style/:filename",
:storage => :s3,
:s3_credentials => {
  :bucket => ENV['S3_BUCKET_NAME'],
  :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
  :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
  }
}

# user.rb model
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
has_attached_file :cover_image, :styles => { :large => "900x900#" }

# Using devise so this is all I have for the user. It handles editing and everything else.
# users_controller.rb
class UsersController < ApplicationController

  def show
    @user = User.find_by_username(params[:username])
    Visit.track(@user, request.remote_ip)
  end

  def home
  end

end

# application_controller.rb changes to devise to allow for other fields in forms.
before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(:username, :first_name, :last_name, :email, :password, :password_confirmation)
    end
    devise_parameter_sanitizer.for(:account_update) do |u|
      u.permit(:username, :first_name, :last_name, :bio, :email, :password, :password_confirmation, :current_password, :avatar, :cover_image)
    end
  end

在头部,我将它显示为用户的个人资料图片,在个人资料中,我使用了与头部相同的代码。在这个链接中,这里是个人资料和带有个人资料图片的头部的图片:http://4stor.com/ujp7F 但是,当使用@user对象而不是来自设备的current_user对象时,它返回像这样的URL:“/avatars/thumb/missing.png”,而不是获取S3 URL。但问题是,它存在...它在头部中显示。
我非常困惑,在这里毫无线索,不知道什么原因导致paperclip抓取此URL而不是正确的URL。StackOverflow上的其他答案并没有帮助,但类似的问题有。谢谢! :)

请分享控制器中相关的代码。将其添加到问题中。 - Kirti Thorat
感谢分享代码。请看我的回答。 - Kirti Thorat
1个回答

1
如果使用@user.avatar.url(:thumb)无法看到头像,则表示在此情况下所引用的@user用户记录没有相关联的头像。因此,出现了missing.png
这里有一个思考题,您可以通过以下方式检查current_user@user:
  def show
    @user = User.find_by_username(params[:username])
    puts @user.inspect  ## See which record @user is referring to, check if it has an avatar
    Visit.track(@user, request.remote_ip)
  end

你也可以执行 puts current_user.inspect 命令来查看 current_user 的信息。
简而言之,current_user@user 指向的不是同一条记录。
请告诉我你的 inspect 结果。

谢谢!这很有效...下次我遇到像这样的问题,我一定会试试这个方法。我的current_user和我试图查看的profile(我的个人资料)完全不同。我重置了我的数据库,现在一切都好了。非常感谢 :) - g33kidd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接