我正在尝试在模型虚拟属性中使用预定义常量。
当我创建用户时,它显示绝对avatar_url
并且工作正常。
问题:
当我在登录方法中找到用户时,它只返回相对url
,即"avatar_url": "/avatars/original/missing.png"
,这意味着#{SERVER_BASE_PATH}
当时没有插值。
在更新用户时,它也适用于api
次呼叫。但并非在所有情况下。请帮助我如何解决此问题,以便在所有api
来电中获取绝对网址
示例:
型号:
class User < ApplicationRecord
# user model
# if avatar url is empty then use default image url
# SERVER_BASE_PATH is defined in config/initializer/constant.rb
attribute :avatar_url, :string, default: -> { "#{SERVER_BASE_PATH}/avatars/original/missing.png" }
end
控制器:
它有简单的登录方法
class UsersController < ApplicationController
def login
response = OK()
unless params[:email].present? and params[:password].present?
render json: missing_params_specific('either user [email] or [password]') and return
end
response[:user] = []
response[:status] = '0'
begin
user = User.find_by(email: params[:email].downcase)
if user && user.authenticate(params[:password])
# following line first check if user profile image exist then it places that image url given by paperclip
# if not exist then url defined in model virtual attributes is used.
user.avatar_url = user.avatar.url if user.avatar.url.present?
user.set_last_sign_in_at user.sign_in_count
response[:user] = user
response[:status] = '1'
else
response[:message] = 'Invalid email/password combination' # Not quite right!
end
rescue => e
response[:message] = e.message
end
render json: response and return
end
end
API JSON响应:
{
"JSON_KEY_STATUS_CODE": 1,
"JSON_KEY_STATUS_MESSAGE": "OK",
"server_time": 1490623384,
"user": {
"confirmed": true,
"user_status": "Active",
"admin": false,
"user_role": "Standard",
"first_name": "Super",
"last_name": "User",
"full_name": "Super User",
"avatar_url": "/avatars/original/missing.png", <-- Here (not absolute url)
"is_active": true,
},
"status": "1"
}
答案 0 :(得分:1)
根据我的理解,您的JSON响应中的"avatar_url"
属性是您在模型上定义的default_url
,您将Paperclip与:
class User < ActiveRecord::Base
has_attached_file :avatar,
styles: { medium: "300x300>", thumb: "100x100>" },
default_url: "/images/:style/missing.png"
validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/
end
您是否尝试与default_url
一起设置SERVER_BASE_PATH
?