我试图在Model虚拟属性中使用预定义的常量。
当我创建用户时,它显示了绝对的avatar_url,并且工作正常。
问题:
当我在登录方法中找到用户时,它只返回相对的url,即"avatar_url": "/avatars/original/missing.png",这意味着#{SERVER_BASE_PATH}在那一刻没有内插。
在更新用户时,它也可以很好地处理一些api调用。但并不是所有的情况。请帮助我解决这个问题,以便在所有api调用中获得绝对的url。
示例:
模型:
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
endAPI响应:
{
"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"
}发布于 2017-03-27 14:58:17
据我所知,JSON响应上的"avatar_url"属性是您在您的模型上定义的default_url,与之集成如下:
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吗
https://stackoverflow.com/questions/43049107
复制相似问题