多くの投稿があるストーリー モデルがあります。
story.rb
:
has_many :posts, :dependent => :destroy
post.rb
:
belongs_to :story, :touch => true
AJAX を使用してstories#index
アクションに get 要求を行い、そのアクションで、検索パラメーターに準拠するストーリーの配列で構成される応答を生成します。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
そのストーリーに属する最新の投稿で構成される追加の属性 が含まれるようにします。相対的なオブジェクト指向として、この新しい属性/関連付けを含めるようにストーリー オブジェクトを変更するのに問題があります。これは、ストーリー オブジェクトと共に応答の一部としてレンダリングされます。
どんな助けでも大歓迎です!
編集:
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