如何在渲染操作中包含关联的对象

时间:2013-03-04 18:43:59

标签: ajax ruby-on-rails-3 has-many belongs-to

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

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

1 个答案:

答案 0 :(得分:0)

我在rabl gem的帮助下解决了这个问题。提出正确的DSL语法证明了一点点试错。关键是在object false视图中使用stories/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