本示例假定您具有创建Rails应用程序的经验。
要在Rails 5中创建仅API的应用,请运行
rails new name-of-app --api
在Gemfile中添加active_model_serializers
gem 'active_model_serializers'
在终端安装捆绑软件
bundle install
设置ActiveModelSerializer适配器以使用:json_api
# config / initializers / active_model_serializer.rb ActiveModelSerializers.config.adapter = :json_api Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest application/vnd.api+json )
为您的资源生成一个新的支架
rails generate scaffold Task name:string description:text
这将生成以下文件:
控制器:app / controllers / tasks_controller.rb
Test: test/models/task_test.rb test/controllers/tasks_controller_test.rb Routes: resources :tasks added in routes.rb Migration: db/migrate/_create_tasks.rb Model: app/models/task.rb Serializer: app/serializers/task_serializer.rb Controller: app/controllers/tasks_controller.rb