2013-03-04 25 views
0

我有了很多帖子故事模型的关联对象:如何包括在渲染动作

story.rb

has_many  :posts, :dependent => :destroy 

post.rb

belongs_to :story, :touch => true 

我使用AJAX来使一个获取我的stories#index动作的请求,并且在该动作中,我生成一个响应,其中包含符合我的搜索参数的故事数组。我包括我的回答一些额外的数据,如是否有一个current_user,并通过我的搜索寻找的故事日期:

def index 
    ajax_response = {} 
    ajax_response[:currentUser] = user_signed_in? ? current_user : "no current user" 
    searched_through_date = Stories.last.created_at 
    @stories = get_stories(params,searched_through_date) 
    if @stories && @stories.length << 200 
     ajax_response[:stories] = @stories 
     ajax_response[:searched_through_date] = searched_through_date 
    else #only happens if there are too many responsive stories 
     ajax_response[:error] = {:type => "Response too large", :number_of_stories => @stories.length } 
    end 
    render :json => ajax_response 
    end 

现在我想改变的响应,使每个故事,我返回还有一个附加属性:latest_post,它由属于该故事的最新帖子组成。作为一个相对的nOOb,我无法修改故事对象,以便它们包含这个新的属性/关联,然后将其与故事对象一起呈现为响应的一部分。

任何帮助将不胜感激!

编辑:

这里是get_stories方法的相关部分:

def get_stories(params) 
    q = get_story_search_params(params) 
    Story.search_with_params(q).limit(q[:limit]).offset(q[:offset]) 
    end 

    def get_story_search_params(params) 
    q = {} 
    q[:limit] = params[:limit].blank? ? 25 : params[:limit].to_i 
    q[:text_to_search] = params[:text_to_search].blank? ? nil : params[:text_to_search] 
    q[:offset] = params[:offset].blank? ? 0 : params[:offset] 
    return q 
    end 
+0

你或许应该包括你的'get_stories'方法的代码,因为这就是产生'@ stories'集合(这是你想修改什么)。 – MrTheWalrus 2013-03-04 21:53:36

+0

我将编辑问题以包含代码,但该方法仅返回一个故事对象数组。 @MrTheWalrus指出我想修改该数组中的故事对象是正确的。 – 2013-03-04 23:25:52

回答

0

我解决了这个问题与Rabl的宝石的帮助。使用正确的DSL语法证明了一点点的反复试验。关键是在stories/index.json.rabl视图中使用object false,并很好地使用了拉布尔偏压。希望它可以帮助别人,我已经在此附上了我的工作代码。

#stories/index.json.rabl 

object false 

node(:currentUser) do 
    if user_signed_in? 
    partial('users/show', :object => current_user) 
    else 
    "no current user" 
    end 
end 

node(:stories) do 
    partial('stories/list', :object => @stories) 
end 

node(:searched_through_date) { |m| @searched_through_date } 

#stories/show.json.rabl 

object @story 

attributes :address, :category, :created_at, :username 

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

#stories/list.json.rabl 

collection @stories, :object_root => "story" 

extends "stories/show" 

#user/show.json.rabl 

object @user 

node :user do |u| 
    { :email => u.email, :username => u.username, :preferred_post_to_facebook => u.preferred_post_to_facebook, 
    :preferred_tweet_to_twitter => u.preferred_tweet_to_twitter, :home_address => u.home_address, 
    :home_lat => u.home_lat, :home_lng => u.home_lng, :suspended => u.suspended } 
end