【发布时间】:2016-06-16 09:20:56
【问题描述】:
您好,我正在使用 Ruby on Rails 创建一个 api。
我正在使用回形针宝石。
我有一个有头像的profile 模型。如何允许用户上传头像?目前我很迷茫。问题是我可以让这个架构工作。我是初学者,所以任何帮助都会很棒。我真的不确定如何获取 base64 转换后的图像并将图像存储在数据库中。
我的Profile模特:
class Profile < ActiveRecord::Base
belongs_to :user
validates :user, presence: true
before_validation :set_image
has_attached_file :avatar, styles: {thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
#image_json is the image in base64 string
def set_image
StringIO.open(Base64.decode64(image_json)) do |data|
data.class.class_eval { attr_accessor :original_filename, :content_type }
data.original_filename = "file.gif"
data.content_type = "image/gif"
self.avatar = data
end
end
end
这是我的更新操作:当前配置文件没有头像,我正在尝试用一个更新它。
def update
if @profile.update(profile_params)
render json: @profile, status: :ok
else
render json: json_errors(@profile.errors), status: :unprocessable_entity
end
end
架构
create_table "profiles", force: :cascade do |t|
t.integer "user_id"
t.date "birthday"
t.text "bio"
t.string "phone"
t.string "address_line_1"
t.string "address_line_2"
t.string "suburb"
t.string "state"
t.string "postcode"
t.string "country_code"
t.string "first_name"
t.string "last_name"
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
end
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4