[英]Rails 5 Constant & Model & Virtual Attributes
我试图在Model虚拟属性中使用预定义常量。
当我创建用户时,它显示绝对的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"
}
据我了解,JSON响应上的"avatar_url"
属性是您在将Paperclip与以下模型集成的模型上定义的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
您是否尝试使用SERVER_BASE_PATH
设置default_url
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.