I have a post model that has a virtual attribute that I would like to set and then include in a response to a JSON call to my post#index action. I can’t seem to get the virtual attribute to be included in the response.
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
I think that I must need something similar to @post.to_json(:methods => %w(m_width)), but I don’t see how to use :methods in a respond_with
This seems to provide the answer. Implement ato_jsonandto_xmlin your models, as appropriate, with definitions like:There’s a better answer implied here.
Following code stolen from the post:
to_jsonwon’t be called on your model in this case, from what I can tell in the source, butas_jsonwill be, in the process of serialization.So, here’s what happens, in overview form:
respond_withwith the results hash you’ve constructed.to_jsonsends you over to JSON::Encoding which keeps callingas_jsonall the way down until everything is JSONified.That’s why there was the confusion about
to_jsonandas_jsonin an earlier version of this answer.