モデル仮想属性で定義済みの定数を使用しようとしています。Rails 5定数とモデルと仮想属性
私はユーザーを作成すると、それは絶対avatar_url
を示し、正常に動作します。
問題:私は、ログイン方法でユーザーを見つけたとき
それは#{SERVER_BASE_PATH}
は、その時点で補間されていないことを意味だけ相対url
すなわち"avatar_url": "/avatars/original/missing.png"
を返します。
また、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
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"
}
[rails asset helpers](http://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html#method-i-path_to_asset)を使用して、/public'を使用する代わりに? – max
rails apiを使用しています。資産パイプラインAFAIKはありません。 –