Rails 模型中的自定义非数据库属性未返回到 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 调用似乎只是返回由 activeRecord 自动生成的游戏属性。它似乎没有发回“opponent_nickname”。
有什么想法吗?
谢谢
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_nickname'.
Any ideas why?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
默认的 json 序列化器来自 ActiveRecord,您需要将新属性添加到对象的 json 表示形式中。
Try this:
The default json serializer comes from ActiveRecord, you need to add the new attribute to the json representation of the object.