How to calculate a field based on retrieved fields and incorporate into JSON in rails -
i have controller method retrieves data 1 table based on userid. want simple addition of 2 of integer fields in table user , have part of returned json. have far:
def show @user = user.find(params[:id]) respond_to |format| # here need remove layout because request # done via ajax , layout loaded. format.json { render json: @user.to_json } end
the fields want add make new field 'score1' , 'score2'. assume have @user.overallscore = @user.score1 + @user.score2
you can define instance method score_sum
in user
model
def score_sum self.score1 + self.score2 end
and use @user.to_json(:methods => [:score_sum])
in controller.
Comments
Post a Comment