用户上传的背景?

ahu*_*ng7 1 ruby ruby-on-rails background-image css3

我希望用户能够上传图像以用作他们的个人资料(用户#show).查看具有该功能的一些站点的源(例如Twitter),似乎为用户分配了html body标签,并且该body标签的相应CSS background-image链接到他们已上载的图像.

有关如何做到这一点的任何想法?(注意:我目前正在使用paperclip进行图片上传,但会将其与Amazon S3 /类似服务集成)

我想过从我的用户控制器向一个CSS文件/脚本注入一个ruby实例变量,以便它是动态的,但我不知道这是否可能.可能有更好的方法.

Chr*_*ini 6

我在项目中实现了类似的东西.我将放下这个概念并给你一个代码示例.我将让您了解逻辑或采用代码示例,以适应您的系统实现.

我会用这个帮手.

app/views/layouts/application.html.erb中

<head>
  ...
</head>
<body style="<%= show_user_bg %>">
  ...
</body>
Run Code Online (Sandbox Code Playgroud)

app/helpers/application_helper.rb中

module ApplicationHelper
  def show_user_bg
    "background:transparent url(#{@user.background_image}) no-repeat fixed left top;"
  end
end
Run Code Online (Sandbox Code Playgroud)

只需确保您的用户模型具有background_image列并已设置.

使用帮助器使其更加动态和清洁.例如,你可以投入条件:

module ApplicationHelper
  def show_user_bg
    # Show user background
    if user_signed_in?
      "background:transparent url(#{@user.background_image}) no-repeat fixed left top;"
    # Otherwise, show a default background image
    else
      "background:transparent url('/images/default_bg.png') no-repeat fixed left top;"
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!