#4 Add user serializer

This commit is contained in:
2015-10-06 21:59:08 +08:00
parent 8484ad769a
commit 7fc1e2c5fc
6 changed files with 30 additions and 2 deletions
@@ -3,7 +3,7 @@ class Api::V1::ApplicationController < ActionController::Base
skip_before_action :verify_authenticity_token
serialization_scope :current_user!
serialization_scope :view_context
before_action :current_user!
before_action :authenticate_user_from_token
@@ -1,8 +1,21 @@
class Api::V1::UsersController < Api::V1::ApplicationController
before_action :load_user, except: [:me]
def show
render json: @user, serializer: UserSerializer
end
def me
render json: @current_user
end
private
def load_user
@user = User.find_by id: params[:id]
render json: {msg: '不能找到该用户'}, status: 404 unless @user
end
end
+1 -1
View File
@@ -1,7 +1,7 @@
class ApplicationController < ActionController::Base
include ActionController::Serialization
serialization_scope :current_user!
serialization_scope :view_context
before_action :current_user!
def current_user!
+4
View File
@@ -21,6 +21,10 @@ class User < ActiveRecord::Base
User.where(id: user_ids)
end
def followers_ids
FollowRelation.where(star_id: self.id).pluck(:user_id)
end
def active_auth_token
if auth_tokens.empty?
generate_auth_key
+9
View File
@@ -1,4 +1,13 @@
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :email, :followed
def followed
return true if object == scope.current_user
object.followers_ids.include? scope.current_user
end
end
+2
View File
@@ -78,6 +78,8 @@ Rails.application.routes.draw do
get '/top/:type', to: 'dashboard#top'
get '/top', to: 'dashboard#top_all'
get '/users/me', to: 'users#me'
resources :users, only:[:show] do
resources :follow, only: [:create]
post :unfollow, to: 'follow#destroy'