我有一个post模型,它有一个我想要设置的虚拟属性,然后包含在对我的post #index action的JSON调用的响应中。我似乎无法将虚拟属性包含在响应中。
class Post < ActiveRecord::Base
attr_accessible :height
attr_accessor :m_height
end
class PostsController < ApplicationController
respond_to :html, :json, :js
def index
story = Story.find(params[:story_id])
@posts = story.posts.where("posts.id >= ?", 100)
@posts.each do |post|
post.m_width = post.height * 200
end
results = { :total_views => story.total_views,
:new_posts => @posts }
respond_with(results)
end
end
我认为我必须需要与@post.to_json(:methods => %w(m_width))
类似的东西,但我不知道如何使用:respond_with中的方法
答案 0 :(得分:1)
This似乎提供了答案。根据需要在模型中实施 to_json
和to_xml
,其定义如下:
有一个更好的答案隐含here。
以下代码从帖子中窃取:
def as_json(options={})
super(options.merge(:methods => [...], :only => [...], :include => [...])
end
在这种情况下, to_json
不会在我的模型中调用,我可以在source中看到,但as_json
将在序列化过程中被调用。
所以,这是以概述形式发生的事情:
respond_with
。to_json
sends you over to JSON::Encoding一直调用as_json
,直到所有内容都被JSON化。这就是为什么在此答案的早期版本中存在关于to_json
和as_json
的混淆。