ruby-on-rails - 用户上传的背景?

标签 ruby-on-rails ruby css background-image

我希望用户能够上传图片作为他们个人资料的背景 (users#show)。查看一些具有该功能的网站(例如 Twitter)的源代码,似乎为用户分配了一个 html 主体标签,并且该主体标签的相应 CSS 背景图像链接到他们上传的图像。

关于如何执行此操作的任何想法? (注意:我目前正在使用回形针上传图片,但会将其与 Amazon S3/类似服务集成)

我考虑过从我的用户 Controller 向 CSS 文件/脚本注入(inject)一个 ruby​​ 实例变量,以便它是动态的,但我不知道这是否可行。可能有更好的方法。

最佳答案

我在一个元素中实现了类似的东西。我将阐述这个概念并给你一个代码示例。我会让您理解逻辑或使用一些代码示例来适合您的系统实现类型。

我会为此使用助手。

app/views/layouts/application.html.erb

<head>
  ...
</head>
<body style="<%= show_user_bg %>">
  ...
</body>

app/helpers/application_helper.rb

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

只需确保您的用户模型具有 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

希望对您有所帮助!

关于ruby-on-rails - 用户上传的背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5659540/

相关文章:

ruby-on-rails - 如何从 Visual Studio Code 运行和调试 Ruby on Rails?

ruby-on-rails - 如何让 RSpec 测试子目录中的 Controller ?

ruby-on-rails - 尝试添加 accepts_nested_attributes_for 时缺少 fields_for

ruby-on-rails - 如何在 Rails 5 的路由中使用环境变量

ruby - 无法将 nil 转换为字符串

css - 通过 css 的文本装饰线在我的 "completed"类的 Safari 上不起作用

ruby-on-rails - 如何将 AngularJS 与 Rails 表单一起使用?

ruby-on-rails - ActiveRecord::Base.connection.execute 一次只执行一条语句吗?

python - 如何使用 setStyleSheet 更改 QLabel 小部件的字体大小(以百分比为单位)?

css - 在 css 中,当 css 使用 border-radius 属性生成圆时,然后在边框上添加虚线