I have the following model
class Game < ActiveRecord::Base
# Associations
belongs_to :black_member, :class_name => "Member"
belongs_to :white_member, :class_name => "Member"
belongs_to :current_move_member, :class_name => "Member"
belongs_to :game_requests, :foreign_key => "game_request_id"
#Validations
#attr_accessible :opponent_nickname, :current_member_id
# Instance methods
attr_accessor :opponent_nickname, :current_member_id
def setup
if self.white_member_id == self.current_member_id
self.opponent_nickname = "test"
end
end
end
My controller:
# POST /games/setup.json
def setup
@game = Game.find(params[:id])
@game.current_member_id = currentmember.id
@game.setup
respond_to do |format|
format.json { render :json => @game }
end
end
And my js function that sends & receives ajax request to controller:
// Setup all initial game details on game startup
SITE.Game.LoadGameDetails = function() {
gameId = $(".edit_game").attr("id").split('_')[2];
$.post('/games/setup', {id: gameId},
function(result) {
console.log("opp = " + result.opponent_nickname);
}
,"json");
}
For some reason my ajax call only seems to be return game attributes that are automatically generated by activeRecord. It doesn't seem to be sending back the 'opponent_n开发者_JAVA百科ickname'.
Any ideas why?
Thanks
Try this:
render :json => @game.to_json(:methods => :opponent_nickname)
The default json serializer comes from ActiveRecord, you need to add the new attribute to the json representation of the object.
精彩评论