Start on Rails5.0 API

Install

Rails5.0需要ruby2.2.3以上版本

rvm install 2.3.0

gem install rails -v 5.0.0.beta3 --pre

Create

我们要做一个前后端分离的应用,后端只需要返回json,前端使用ReactJS来做渲染。

rails new ToySweet --api

rails5.0的api创建模式使得项目精简了,去掉了rails与浏览器相关的一些功能,例如:

This includes things like sessions, cookies, assets, and really anything related to making Rails work with a browser.
Ref: https://blog.codeship.com/building-a-json-api-with-rails-5/

通过对比中间件(rake middleware),我们可以看到api模式下使用的中间件减少了几项

use Rack::MethodOverride
use WebConsole::Middleware
use ActionDispatch::Cookies
use ActionDispatch::Session::CookieStore
use ActionDispatch::Flash

同时去掉了view,并且ApplicationController继承自ActionController::API

Database

Database使用Postgres, 在Gemfile中加入

gem 'pg'

然后

bundle install

并将config/database.yml中内容替换为

default: &default  
    adapter: postgresql  
    encoding: unicode  
    pool: 5

development:  
    <<: *default  
    database: toysweet_development

test:  
    <<: *default  
    database: toysweet_test

production:  
    <<: *default  
    database: toysweet_production
    username: toysweet  
    password: <%= ENV['TOYSWEET_DATABASE_PASSWORD'] %>

JSON Is Everything

加入active_model_serializers用来定义返回的JSON格式

gem 'active_model_serializers', '~> 0.10.0.rc1'

生成脚手架listing

rails g scaffold listing content:text title:string

生成的信息如下

invoke  active_record
create    db/migrate/20160319091211_create_listings.rb
create    app/models/listing.rb
invoke    test_unit
create      test/models/listing_test.rb
create      test/fixtures/listings.yml
invoke  resource_route
route    resources :listings
invoke  serializer
create    app/serializers/listing_serializer.rb
invoke  scaffold_controller
create    app/controllers/listings_controller.rb
invoke    test_unit
create      test/controllers/listings_controller_test.rb

别忘了还要做一下migrate。Rails5.0中可以统一用rails来替代rake,所以

rails db:
rails db:setup
rails db:migrate

现在访问http://localhost:3000/listings/1,就可以获得listing

{
  data: 
      {
       id: "1",
       type: "listings",
       attributes: 
             {
                content: "nice thing",
                title: "Dog Tower"
             }
       }
}

模型关系

一个user可以有多个listing,而一个listing只属于某一个user

再生成另一个模型User

rails g scaffold user name:string email:string

并在Listing和User中分别添加association

#listings.rb
class Listing < ApplicationRecord  
  belongs_to :user
end

#users.rb
class User < ApplicationRecord
  has_many :listings
end

添加migration

#terminal
rails g migration add_references_to_listings user:references
rails db:migrate

此时两个model间的关联已经建立,于是我们可以这样子创建一个包含有listing的user

#terminal中运行rails c
user = User.create(name: 'Wang Zhiming', email: '[email protected]')
user.listings.create(title: 'Bike', content: 'Good to have!')

此时访问http://localhost:3000/user/1并不会返回user1包含的listing内容,这是因为返回的json内容是由active_model_serializers来做配置的。

于是做以下修改

#user_serializer.rb
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :email
  has_many :listings
end

#listing_serializer.rb
class ListingSerializer < ActiveModel::Serializer
  attributes :id, :content, :title
  belongs_to :user
end

此时再访问http://localhost:3000/user/1不光可以得到user1的内容,还能得到其包含的listing的内容

你可能感兴趣的:(Start on Rails5.0 API)