When we use rails generate scaffold to generate MVC, rails will automatically generate a series of files for us, including how to display the Model View in JSON. By default, your system is a crud system, but we know that restful is not a crud system. Exposing the model directly is not a good choice.
Rabl is a DSL that allows you to easily customize the display information of the generated object GEM: https://github.com/nesquena/rabl
The procedure is as follows:
1. First create a new rails project:
Rails new rabl-app
2. Add the rabl dependency to gemfile:
Gem 'rabl'
3. Create a model:
Rails G model blog title: String Author: String content: Text
4. database migration:
Rake DB: migrate
5. Create a controller:
Create a new empty file blogs_controller.rb under APP/Controllers
The content is as follows:
Class blogscontroller <applicationcontroller
Def Index
@ Blogs = blog. All
End
Def show
@ Blog = blog. Find (Params [: Id])
End
End
Stub data can be used for testing:
@ Blog = blog. new ({: Id => 3,: Title => "Good title",: Author => "Good author",: content => "good content "})
6. Create the view corresponding to rabl:
Create a new empty folder blogs under APP/views:
Create two new files under APP/views: Index. JSON. rabl and show. JSON. rabl.
Show. JSON. rabl:
Object @ blog
Attributes: ID,: title,: Author,: Content
Index. JSON. rabl:
Collection @ blogs
Extends "blogs/Show"
7. Configure route
In routes. RB:
Rails. application. routes. Draw do
Resources: blogs
End
8. Start Server
Rails s
Access: http: // localhost: 3000/blogs/3. JSON
Expected result:
{"blog":{"id":3,"title":"good title","author":"good author","content":"good content"}}
The above example demonstrates how to use rabl in rails. It does not mean that the display method above is a good method for constructing object reality. For more information, see:
Https://github.com/nesquena/rabl
Http://railscasts.com/episodes/322-rabl? View = similar