在响应JSON调用时包含虚拟属性

时间:2012-12-30 04:52:35

标签: ruby-on-rails ruby-on-rails-3

我有一个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中的方法

1 个答案:

答案 0 :(得分:1)

This似乎提供了答案。根据需要在模型中实施to_jsonto_xml,其定义如下:

有一个更好的答案隐含here

以下代码从帖子中窃取:

  def as_json(options={})
    super(options.merge(:methods => [...], :only => [...], :include => [...])
  end
在这种情况下,

to_json不会在我的模型中调用,我可以在source中看到,但as_json将在序列化过程中被调用。

所以,这是以概述形式发生的事情:

  1. 使用您构建的结果哈希调用respond_with
  2. Rails(ActionController)calls to_json就此而已。
  3. to_json sends you over to JSON::Encoding一直调用as_json,直到所有内容都被JSON化。
  4. 这就是为什么在此答案的早期版本中存在关于to_jsonas_json的混淆。