2016-06-07 6 views
1
내 시리얼 라이저 사용자 정의 레코드에 대한 불완전 필드를 얻고있다

표시되지 않는 속성사용자는 활성 모델에 시리얼

class MatchSerializer < ApplicationSerializer 
    attributes :id, :player1, :player2, :match_type, :status, :winner, :score, :match_categories 

    def match_categories 
    #adds international category array to the intersection of player1 and player2 category arrays 
    #this is done so that players playing against other countries player will allways 
    #play at least international categories and any other categories common to both 

    Category.where(country_id: 1) + 
(Category.where(country_id: object.player1.country) & Category.where(country_id: object.player2.country)) 
    end 

end 

카테고리를 렌더링 할 때 전체 필드가 ​​JSON 응답으로 표시됩니다.

{ 
    "data": [ 
    { 
     "id": "1", 
     "type": "categories", 
     "attributes": { 
     "name": "Sports", 
     "localized_name": "Deportes", 
     "picture": "default_url", 
     "status": "active", 
     "visible": false, 
     "country": { 
      "id": 1, 
      "name": "International", 
      "country_code": "NA", 
      "picture": "default_url", 
      "language_code": "en", 
      "status": "active", 
      "visible": false, 
      "created_at": "2016-06-06T16:12:29.701Z", 
      "updated_at": "2016-06-06T16:12:29.701Z" 
     } 
     } 
    }, 

일치를 렌더링 할 때 일치 serializer는 일치에 관련된 범주의 배열을 계산하고 각각에 대한 범주 정보를 렌더링합니다. 그러나 알 수 있듯이 카테고리 맞춤 입력란 : localized_name은 포함되지 않습니다.

>{ 
    "data": [ 
    { 
     "id": "1", 
     "type": "matches", 
     "attributes": { 
     "player1": { 
      "id": 1, 
      "provider": "email", 
      "uid": "[email protected]", 
      "country_id": 2, 
      "name": null, 
      "first_name": null, 
      "last_name": null, 
      "gender": null, 
      "fb_auth_token": null, 
      "nickname": null, 
      "image": null, 
      "email": "[email protected]", 
      "friend_count": null, 
      "friends": null, 
      "status": "active", 
      "premium": null, 
      "created_at": "2016-06-06T16:13:58.711Z", 
      "updated_at": "2016-06-06T16:14:15.722Z" 
     }, 
     "player2": { 
      "id": 2, 
      "provider": "email", 
      "uid": "[email protected]", 
      "country_id": 2, 
      "name": null, 
      "first_name": null, 
      "last_name": null, 
      "gender": null, 
      "fb_auth_token": null, 
      "nickname": null, 
      "image": null, 
      "email": "[email protected]", 
      "friend_count": null, 
      "friends": null, 
      "status": "active", 
      "premium": null, 
      "created_at": "2016-06-07T08:03:38.472Z", 
      "updated_at": "2016-06-07T08:03:38.611Z" 
     }, 
     "match_type": "Duel", 
     "status": "active", 
     "winner": null, 
     "score": null, 
     **"match_categories": [ 
      { 
      "id": 1, 
      "country_id": 1, 
      "name": "Sports", 
      "picture": "default_url", 
      "status": "active", 
      "visible": false, 
      "created_at": "2016-06-06T16:12:29.893Z", 
      "updated_at": "2016-06-06T16:12:29.893Z" 
      }, 
      { 
      "id": 2, 
      "country_id": 2, 
      "name": "Futbolistas Peruanos", 
      "picture": "default_url", 
      "status": "active", 
      "visible": false, 
      "created_at": "2016-06-06T16:12:29.961Z", 
      "updated_at": "2016-06-06T16:12:29.961Z" 
      }, 

이 시나리오에서 표시 할 수있는 localized_name 필드는 어떻게 얻을 수 있습니까?

EDIT : 요청 된 컨트롤러. 예쁜 표준

class MatchesController < ApplicationController 
    before_action :set_match, only: [:show, :update, :destroy] 

# GET /matches 
    def index 
    @matches = Match.all 

    render json: @matches 
    end 

    # GET /matches/1 
    def show 
    render json: @match 
    end 

    # POST /matches 
    def create 
    @match = Match.new(match_params) 

    #if player1 not explicitly included will set player1 as uid header of API call 
    @match.player1_id ||= current_user.id 
    #if player2 parame set as random will generate random user from all curently active users 
    if params[:match][:player2_id] == 'random' 
     #call model method that returns a random array of userids to play as player 2 but 
     #passing player1_id so that method will remove it from possible responses 
     #since player1 cannot play itself 
     @match.player2_id = @match.active_random_player2(@match.player1_id) 
    end 

    if @match.save 
     render json: @match, status: :created, location: @match 
    else 
     render json: @match.errors, status: :unprocessable_entity 
    end 
    end 

    # PATCH/PUT /matches/1 
    def update 
    if @match.update(match_params) 

     render json: @match 
    else 
     render json: @match.errors, status: :unprocessable_entity 
    end 
    end 

    # DELETE /matches/1 
    def destroy 
    @match.destroy 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_match 
     @match = Match.find(params[:id]) 
    end 

    # Only allow a trusted parameter "white list" through. 
    def match_params 
    params.require(:match).permit(:player1_id, :player2_id, :match_type, :bet, :status, :winner, :score) 
    end 
end 


class CategoriesController < ApplicationController 
    before_action :set_category, only: [:show, :update, :destroy] 

    # GET /categories/newmatch 
    def newmatch 
    @categories = Category.where(country: current_user.country) 

    render json: @categories 
    end 

    # GET /categories 
    def index 
    if params[:all] && params[:all] != 'false' 
     @categories = Category.all 
    else 
     @categories = Category.where(country: current_user.country) 
    end 

    render json: @categories 

    end 

    # GET /categories/1 
    def show 
    render json: @category 
    end 

    # POST /categories 
    def create 

    @category = Category.new(category_params) 
    if @category.save! 
     render json: @category, status: :created, location: @category 
    else 
     render json: @category.errors, status: :unprocessable_entity 
    end 
    end 

    # PATCH/PUT /categories/1 
    def update 
    if @category.update(category_params) 
     render json: @category 
    else 
     render json: @category.errors, status: :unprocessable_entity 
    end 
    end 

    # DELETE /categories/1 
    def destroy 
    @category.destroy 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_category 
     @category = Category.find(params[:id]) 
    end 

    # Only allow a trusted parameter "white list" through. 
    def category_params 
     #add permitted translation locale parameters based on required translations 
     #resource agnostic method in application controller 
     params.require(:category).permit(:name, :picture, :status, :visible, :country_id, :all) 
    end 
end 

편집 :

나는 match_categories 쿼리 필드에이 정보를 얻을 수 프란체스코 루포의 제안을 시도,하지만 난 여전히 사용자 정의 localized_name 필드를받지 못했습니다.

"match_categories": [ 
      { 
      "object": { 
       "id": 1, 
       "country_id": 1, 
       "name": "Sports", 
       "picture": "default_url", 
       "status": "active", 
       "visible": false, 
       "created_at": "2016-07-08T23:11:43.304Z", 
       "updated_at": "2016-07-08T23:11:43.304Z" 
      }, 
      "instance_options": { 
       "root": false 
      }, 
      "root": false, 
      "scope": null 
      }, 

답변

3

, 쿼리만으로 충분하지 않은 경우 다음을 시도해보십시오.

def match_categories 
    categories = Category.where(country_id: 1) + (Category.where(country_id: object.player1.country) & Category.where(country_id: object.player2.country)) 
    categories.map { |category| CategorySerializer.new(category, root: false) } 
end 

이렇게하면 모든 카테고리가 올바르게 직렬화됩니다.

@Augusto 코멘트에 따르면 active_model_serializer의 업데이트가 필요할 수 있습니다.

+0

안녕하세요. 도움을 주셔서 감사합니다. 그러나 이것도 작동하지 않습니다. 귀하의 제안을 사용하여 얻은 것을 보여주는 편집을 추가했습니다. – Augusto

+1

오늘 최신 버전의 active_model_serializer (0.10.2)로 업그레이드 했으므로 이제 귀하의 답변이 작동합니다! 당신의 도움을 주셔서 감사합니다! – Augusto

+0

기꺼이 도와 드리겠습니다! –

1

당신이 객체의 관계를 이용하여 대 일부 사용자 지정 방법을하고 있기 때문에, 당신은 당신의 방법에 CategorySerializer을 사용해야 할 수도 있습니다 :

당신은 당신의 각 범주를 직렬화 할 필요가
def match_categories 
    categories = Category.where(country_id: 1) + (Category.where(country_id: object.player1.country) & Category.where(country_id: object.player2.country)) 
    CategorySerializer.new(categories) 
end 
+0

나는 당신의 솔루션을 시도했지만 똑같은 것을 출력합니다. 렌더링이 일치 할 때 여전히 맞춤 localized_name 입력란이 없습니다. – Augusto

+0

컨트롤러를 게시 할 수 있습니까? – danielrsmith

+0

ams를 (0.10.2)로 업그레이드하면이 대답은 거의 작동하지만 내 쿼리가 배열을 반환하기 때문에 오류가 발생합니다. Francesco Lupo의 답은이를 고려합니다 (따라서 맵 기능). 어쨌든 도움을 주셔서 감사합니다. 그 답은 다른 유스 케이스에도 유효합니다. – Augusto