2011-03-18 38 views
2

我有以下型號在鐵軌模型定製非DB屬性不會返回到jQuery的回調

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 

我的控制器:

# 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 

我的js函數發送&接收Ajax請求控制器:

// 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"); 
    } 

由於某種原因,我的ajax調用似乎只是返回n由activeRecord自動生成的遊戲屬性。它似乎沒有送回'opponent_nickname'。

任何想法爲什麼?

感謝

回答

6

試試這個:

render :json => @game.to_json(:methods => :opponent_nickname) 

默認JSON序列來自ActiveRecord的,你需要將新屬性添加到該對象的JSON表示。

+0

完美。謝謝布蘭登。 – 2011-03-18 02:30:44

+0

只是一個音符,要通過mor ethan屬性使用一個數組,如下: 'render:json => @ game.to_json(:methods => [:opponent_nickname,:another_attribute])' – cpuguy83 2012-07-09 18:38:43