仅返回子节点中的第一个子节点

时间:2013-03-06 00:16:22

标签: rabl

我有一个故事模型和一个帖子模型。每个故事都有很多帖子。

在我的故事#index action中我想使用rabl返回所有@stories,@ story中的每个故事也应该包含一个包含最近创建的帖子属性的子节点。

这是我最接近实现我正在寻找的东西:

#show.json.rabl

object @story

attributes  :id, :title, :username

child @story.posts.first => :latest_post do
  attributes  :id, :story_id, :contents, :username
end

这在故事#show action中运作良好。但是,当我尝试用故事#index action

扩展它时
#index.json.rabl

collection @stories

extends "stories/show"

我收到以下错误:

ActionView::Template::Error (undefined method `posts' for nil:NilClass):
    1: collection @stories
    2: 
    3: extends "stories/show"
  app/views/stories/show.json.rabl:8:in `render'

我相信我得到了这个错误,因为我没有设置show.json.rabl视图使用的@story实例变量。但我不知道如何解决这个问题并将show.json.rabl传递给正确的故事对象。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

我用了一个rabl部分来解决问题。方法如下:

#story.show.json.rabl

object @story

attributes  :id, :title, :username

node :latest_post do |story|
  { :post => partial("posts/show", :object => story.posts.first)}
end

#story.index.json.rabl

collection @stories

extends "stories/show"

post.show.json.rabl

object @post

attributes  :id, :story_id, :contents, :username

这完全符合要求。

相关问题