0

我有一个有很多帖子的故事模型:

story.rb

  has_many      :posts, :dependent  =>  :destroy

post.rb

  belongs_to    :story, :touch => true

我使用 AJAX 向我的stories#index操作发出 get 请求,并在该操作中生成一个响应,该响应由一组符合我的搜索参数的 Stories 组成。我在回复中包含了一些额外的数据,例如是否有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
4

1 回答 1

0

我在 rabl gem 的帮助下解决了这个问题。想出正确的 DSL 语法被证明有点容易试错。关键是object falsestories/index.json.rabl视图中使用并充分利用 rabl partials。希望它可以帮助某人,我在这里附上了我的工作代码。

#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
于 2013-03-09T00:00:33.790 回答