Rails + rabl

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.