rails模型中的自定义非db属性未返回到jquery回调

Tho*_*ley 2 jquery activerecord ruby-on-rails ruby-on-rails-3

我有以下型号

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
Run Code Online (Sandbox Code Playgroud)

我的控制器:

# 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
Run Code Online (Sandbox Code Playgroud)

我的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");
    }
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我的ajax调用似乎只是返回由activeRecord自动生成的游戏属性.它似乎没有发回'opponent_nickname'.

有什么想法吗?

谢谢

Bra*_*don 6

试试这个:

render :json => @game.to_json(:methods => :opponent_nickname)
Run Code Online (Sandbox Code Playgroud)

默认的json序列化程序来自ActiveRecord,您需要将新属性添加到对象的json表示中.