Reputation: 3820
I've got the following to_json in my view:
<%=raw @forums.to_json(:methods => [:topic_count, :last_post]) %>;
and in the model I've got the following method:
def last_post
post = ForumPost.joins(:forum_topic).where(:forum_topics => {:forum_id => self.id}).order("forum_posts.created_at DESC").first
return post
end
However ForumPost contains a relation to a ForumTopic (belongs_to :forum_topic
) and I want to include this ForumTopic in my json so I end up with {..., "last_post":{..., "forum_topic":{...}...}, ...}. How can I accomplish this?
Upvotes: 1
Views: 294
Reputation: 1336
Usually it's better to keep that kind of declaration in the Model. You can override the as_json method in your models. This approach allows you to control the the serialization behavior for your entire object graph, and you can write unit tests for this stuff.
In this example I'm guessing that your @forums variable refers to a model called Forum, if i'm wrong hopefully you still get the idea.
class Forum
...
def as_json(options={})
super(methods: [:topic_count, :last_post])
end
end
class ForumPost
...
def as_json(options={})
super(methods: [:forum_topic])
end
end
Upvotes: 1