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
你或许应该包括你的'get_stories'方法的代码,因为这就是产生'@ stories'集合(这是你想修改什么)。 – MrTheWalrus 2013-03-04 21:53:36
我将编辑问题以包含代码,但该方法仅返回一个故事对象数组。 @MrTheWalrus指出我想修改该数组中的故事对象是正确的。 – 2013-03-04 23:25:52