classPostsController<ApplicationController# GET /posts# GET /posts.jsondefindex@posts=Post.allrespond_todo|format|format.html# index.html.erbformat.json{renderjson:@posts}endend# GET /posts/1# GET /posts/1.jsondefshow@post=Post.find(params[:id])respond_todo|format|format.html# show.html.erbformat.json{renderjson:@post}endend# GET /posts# GET /posts.jsondefindex@posts=Post.allrespond_todo|format|format.html# index.html.erbformat.json{renderjson:@posts}endend# GET /posts/1# GET /posts/1.jsondefshow@post=Post.find(params[:id])respond_todo|format|format.html# show.html.erbformat.json{renderjson:@post}endend# POST /posts# POST /posts.jsondefcreate@post=Post.new(params[:post])respond_todo|format|if@post.saveformat.html{redirect_to@post,notice:'Post was successfully created.'}format.json{renderjson:@post,status::created,location:@post}elseformat.html{renderaction:"new"}format.json{renderjson:@post.errors,status::unprocessable_entity}endendend# PUT /posts/1# PUT /posts/1.jsondefupdate@post=Post.find(params[:id])respond_todo|format|if@post.update_attributes(params[:post])format.html{redirect_to@post,notice:'Post was successfully updated.'}format.json{head:no_content}elseformat.html{renderaction:"edit"}format.json{renderjson:@post.errors,status::unprocessable_entity}endendend# DELETE /posts/1# DELETE /posts/1.jsondefdestroy@post=Post.find(params[:id])@post.destroyrespond_todo|format|format.html{redirect_toposts_url}format.json{head:no_content}endendend# GET /posts# GET /posts.jsondefindex@posts=Post.allrespond_todo|format|format.html# index.html.erbformat.json{renderjson:@posts}endend# GET /posts/1# GET /posts/1.jsondefshow@post=Post.find(params[:id])respond_todo|format|format.html# show.html.erbformat.json{renderjson:@post}endend
長いコードになりましたが、ここでの重要部分は以下のコードです。
app/controllers/posts_controller.rb
12345678910
# GET /posts# GET /posts.jsondefindex@posts=Post.allrespond_todo|format|format.html# index.html.erbformat.json{renderjson:@posts}endend
Post.all は現在のデータベース内にあるすべての Posts を、 @posts で呼ばれたインスタンス変数を格納している Post レコードの配列として返します。
<!DOCTYPE html><html><head> <title>Blog</title><%=stylesheet_link_tag"application"%><%=javascript_include_tag"application"%><%=csrf_meta_tags%></head><body style="background: #CCCCCC;"><%=yield%></body></html>