2016-10-12 12 views
0

)user.rbに次のコードを追加しました。jsonレンダリングの問題点(

def as_json(options={}) 
    h = super(:only => [:id, :content, :created_at, :updated_at]) 
    h 
end 

しかし、別のAPIでは、ユーザー名とアドレスも取得する必要があります。しかし、jsonをレンダリングするときにこれらの4つのフィールドを生成します。どうすれば両方の出力を得ることができますか?事前のおかげ

答えて

2

すぎて、ユーザー名とアドレスを返す必要があります2つのAPIは、このAPI

とします

def api1 
    User.first.as_json(user_info: true) 
end 

これは、ユーザー名を返すと

def api2 
    User.first.as_json(user_info: false) 
end 

がuser.rbが

class User < ApplicationRecord 
    def as_json(options = {}) 

    if options[:user_info] == true 
     user = super(:only => [:id, :content, :created_at, :updated_at, :username, :address]) 
    else 
     user = super(:only => [:id, :content, :created_at, :updated_at]) 
    end 
    user 
    end 
end 
も聞かせて対処する必要はありません。
0

に私が任意のより良いアイデアを持っていないが、私はあなたのようなexceptを使用することができると思う:レンダリング時にあなたがそれらを必要としないか、onlyを使用することができたときに@yourVariable.as_json(except: [:username, :address])を使用することができます次に

def as_json(options={}) 
    h = super(:only => [:id, :content, :created_at, :updated_at, :username, :address]) 
    h 
end 

代わりにexcept