当我们使用rails generate scaffold的方式生成MVC的时候,rails会自己主动给我们生成一系列的文件,包含了怎样用json显示model的view。这样事实上默认了你的系统是一个CRUD的系统,可是我们知道RESTful不是CRUD。把model直接暴露出去不是一个非常好的选择。
rabl是一个DSL能够方便定制生成对象的显示信息的gem:https://github.com/nesquena/rabl
以下是详细的操作过程:
1.首先创建一个新的railsproject:
rails new rabl-app
2.在Gemfile中加入rabl的依赖:
gem ‘rabl‘
3.创建Model:
rails g model Blog title:string author:string content:text
4.迁移数据库:
rake db:migrate
5.创建controller:
在app/controllers下创建一个新的空文件blogs_controller.rb
内容例如以下:
class BlogsController < ApplicationController
def index
@blogs = Blog.all
end
def show
@blog = Blog.find(params[:id])
end
end
能够使用stub数据用于測试:
@blog = Blog.new({:id => 3, :title => "good title", :author => "good author", :content => "good content"})
6.创建rabl相应的view:
在app/views下创建一个新的空目录blogs:
在app/views下创建两个新文件:index.json.rabl和show.json.rabl
show.json.rabl:
object @blog
attributes :id, :title, :author, :content
index.json.rabl:
collection @blogs
extends "blogs/show"
7.配置route
在routes.rb中:
Rails.application.routes.draw do
8.启动server
rails s
訪问:http://localhost:3000/blogs/3.json
得到结果:
{"blog":{"id":3,"title":"good title","author":"good author","content":"good content"}}
我们上面的样例仅仅是演示了怎样在rails中使用rabl,并非说上面的显示方法就是好的构造对象现实的方法,很多其它的能够看看:
https://github.com/nesquena/rabl
http://railscasts.com/episodes/322-rabl?
view=similar
原文:http://www.cnblogs.com/gcczhongduan/p/5159342.html