【问题标题】:Heroku + Rails 4 + Paperclip w/ AWS S3 urls not workingHeroku + Rails 4 + 带有 AWS S3 url 的 Paperclip 不起作用
【发布时间】:2014-05-15 22:26:33
【问题描述】:

所以,目前我在获取个人资料页面的头像和个人资料封面图片的 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 对象而不是 devise 中的 current_user 对象时,它会返回如下所示的 URL:“/avatars/thumb/missing.png”,而不是获取 S3 url。但问题是,它存在......它显示在标题中。

我在这里非常傻眼,不知道是什么导致回形针抓取这个网址而不是正确的网址。 StackOverflow 上的其他答案没有帮助,但类似的问题。谢谢! :)

【问题讨论】:

  • 请分享Controller的相关代码。将其添加到问题中。
  • 感谢分享代码。请看我的回答。

标签: heroku ruby-on-rails-4 devise amazon-s3 paperclip


【解决方案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 和我试图查看的个人资料(我的个人资料)完全不同。我重置了我的数据库,现在一切都很好。非常感谢:)
猜你喜欢
  • 2016-05-08
  • 2015-06-27
  • 1970-01-01
  • 2013-02-02
  • 2013-12-23
  • 1970-01-01
  • 2012-05-02
  • 1970-01-01
  • 2012-12-30
相关资源
最近更新 更多