rails api ws
So, you are tasked with using a Rails API back end for your new project and you are not sure where to begin.
因此,您的任务是为新项目使用Rails API后端,并且不确定从哪里开始。
What gems do I install again?! How do I specify that I want to use PostgreSQL?! What the heck is a serializer? I need a log-in feature and totally forgot how to work bcrypt
! [- Commencement of internal screams of frustration -]
我要重新安装什么宝石? 如何指定要使用PostgreSQL? 什么是序列化器? 我需要登录功能,完全忘记了 bcrypt
工作方式 ! [-内部沮丧的尖叫声开始-]
Have no fear, beginner Rails dev, here’s what I need you to do: 1. Take a deep breath, and 2. Use this step-by-step guide as a model to get you started.
不用担心,初学者Rails开发人员,这是我需要您做的:1.深吸一口气,然后2.使用此逐步指南作为入门的模型。
For the purpose of this demo, I will be setting up the back end for an ecommerce app with two models: User and Item. A user has many items they would like to sell, and an item belongs to a user. Okay, let’s start!
就本演示而言,我将为电子商务应用程序的后端设置两种模型: 用户 和项目。 用户有许多他们想出售的物品,而一个物品属于用户。 好的,让我们开始吧!
步骤0.使用“ rails new”命令创建一个新的Rails应用程序 (Step 0. Create a New Rails Application Using ‘rails new’ Command)
Navigate into the folder where you want to store your Rails app. Throw the following command into the terminal to tell Rails that you want to make a new project utilizing PostgreSQL as the database, and that it will be an API.
导航到要存储Rails应用程序的文件夹。 将以下命令放入终端,以告知Rails您要使用PostgreSQL作为数据库来创建一个新项目,并且它将是一个API。
rails new <project-name> --database=postgresql --api
You should already have PostgreSQL installed. If you do not, follow the steps for installation.
您应该已经安装了PostgreSQL。 如果不这样做,请按照安装步骤进行操作 。
Create a new repository on GitHub, navigate
/ cd
into the new rails project directory you just created, and follow the steps GitHub gives you to initialize Git in your new project.在GitHub上创建一个新的存储库,导航
/ cd
进入刚刚创建的新的Rails项目目录,并按照GitHub所提供的步骤在新项目中初始化Git。
![Image for post](https://miro.medium.com/max/9999/1*GhT9UVM0qCSTGDgFMKgq2A.png)
步骤1.启用“ bcrypt”和“ rack-cors” (Step 1. Enable ‘bcrypt’ and ‘rack-cors’)
Navigate into your
Gemfile
, uncomment outgem ‘bcrypt’
andgem ‘rack-cors’
.导航到您的
Gemfile
,取消注释Gemfile
gem 'bcrypt'
和gem 'rack-cors'
。The
bcrypt
gem allows you to use thehas_secure_password
macro that wonderfully takes care of password authentication for you.bcrypt
gem允许您使用has_secure_password
宏,该宏可以为您很好地进行密码身份验证。rack-cors
gem is the middleware that makes the magic of cross-origin AJAX/fetching of data happens.rack-cors
gem是使跨源AJAX /数据获取神奇的中间件。Run
bundle install
in your terminal once completed to install these gems.完成
bundle install
,请在终端中运行bundle install
。Navigate into
config/initializers/cors.rb
, uncomment out theRack::Cors
configuration, and change origins from'example.com'
to'*'
:导航到
config/initializers/cors.rb
,取消注释Rack::Cors
配置,并将源从'example.com'
更改为'*'
:
![Image for post](https://miro.medium.com/max/9999/1*VFJk_P_k2gB83mpbKPZuwA.png)
When you later deploy your app, changing
origin
to your front-end website address will only allow your front end to make fetch requests to your back end. For now, the wildcard'*'
allows for any local host URL to fetch info from your back end.以后部署应用程序时,将
origin
更改为前端网站地址将仅允许前端向后端发出提取请求。 目前,通配符'*'
允许任何本地主机URL从后端获取信息。
步骤2.为您的表生成迁移,模型和资源 (Step 2. Generate Migrations, Models, and Resources for Your Tables)
My database will hold info for two tables:
users
anditems
. This is what I want them to look like:我的数据库将保存两个表的信息:
users
和items
。 这就是我希望他们看起来像的样子:
![Image for post](https://miro.medium.com/max/9999/1*LKJnqeaEhvCwlJRvez3ZCw.png)
Using
rails g resource
, I can generate migrations, models, and resources using the following commands:使用
rails g resource
,我可以使用以下命令生成迁移,模型和资源:rails g resource User username password_digest city state zip:integer email
rails g resource User username password_digest city state zip:integer email
rails g resource Item user:belongs_to name description condition price:integer pickup:boolean shipping:boolean category photo
rails g resource Item user:belongs_to name description condition price:integer pickup:boolean shipping:boolean category photo
If the data type is a string, you don’t need to specify their type following the column name. Adding
user:belongs_to
specifies the relationship between your two tables and sets up a column foruser_id
in youritems
table. Additionally, we use column namepassword_digest
to avoid directly storing passwords as strings.如果数据类型是字符串,则无需在列名称后指定其类型。 添加
user:belongs_to
指定两个表之间的关系,并在items
表中为user_id
设置一列。 另外,我们使用列名password_digest
来避免将密码直接存储为字符串。Next, run
rails db:create
to create the back end andrails db:migrate
to migrate your tables. Then, go to your models to ensure that appropriate relationships (has_many
,belongs_to
) are set up.接下来,运行
rails db:create
创建后端,并rails db:migrate
迁移表。 然后,转到您的模型以确保设置了适当的关系(has_many
,belongs_to
)。
第3步。使用“ bcrypt”并添加一些验证 (Step 3. Put ‘bcrypt’ to Use and Add Some Validations)
The
bcrypt
gem you installed allows you to use a macro calledhas_secure_password
. Add this to your User model since we will be validating the user’s password. While you’re there, add validations foremail
andusername
:您安装的
bcrypt
gem允许您使用名为has_secure_password
的宏。 将此添加到您的用户模型,因为我们将验证用户密码。 在那里,添加对email
和username
验证:
class User < ApplicationRecord
has_many :items
has_secure_password
validates :email, uniqueness: { case_sensitive: false }
validates :username, uniqueness: { case_sensitive: false }
end
Add this point, you should navigate to your
db/seeds.rb
file, generate seed data, and test them inrails console
.添加这一点,您应该导航到
db/seeds.rb
文件,生成种子数据,并在rails console
对其进行测试。
步骤4.生成序列化器 (Step 4. Generate Serializers)
Serializers are what allow you to structure the JSON data that you send out in the format that is most useful for your front end. I will be using
active_model_serializers
for this demo. To start, addgem 'active_model_serializers'
to yourGemfile
and again runbundle install
.串行器使您能够以对前端最有用的格式来构造发送出的JSON数据。 我将在此演示中使用
active_model_serializers
。 首先,将Gemfile
gem 'active_model_serializers'
添加到您的Gemfile
然后再次运行bundle install
。- Use the following commands to generate serializers for User and Item: 使用以下命令为用户和项目生成序列化器:
rails g serializer User
&rails g serializer Item
rails g serializer User
&rails g serializer Item
Navigate to
app/serializers
and set up attributes for your serializer classes. These attributes specify the keys and their corresponding values that you want to send out as JSON. MyUserSerializer
class now looks like this:导航到
app/serializers
并为序列化器类设置属性。 这些属性指定要作为JSON发送的键及其对应的值。 我的UserSerializer
类现在看起来像这样:
class UserSerializer < ActiveModel::Serializer
attributes :id, :username, :city, :state, :zip, :email
end
Note that I am not sending out
created_at
,updated_at
, andpassword_digest
columns. The wonder with serializers is that you can send out just the info that your front end will need and hide the rest.请注意,我没有发送出
created_at
,updated_at
和password_digest
列。 串行器的奇妙之处在于,您可以仅发送前端所需的信息,而隐藏其余信息。My
ItemSerializer
class looks like this:我的
ItemSerializer
类如下所示:
class ItemSerializer < ActiveModel::Serializer
attributes :id, :name, :description, :condition, :price, :pickup, :shipping, :category, :photo, :user belongs_to :user
end
Specifying
belongs_to :user
here and including:user
as an attribute makes it so that when I send a request to fetch an item, the data I get back will have the following format:在这里指定
belongs_to :user
并包括:user
作为属性,这样可以使我在发送请求以获取项目时,返回的数据将具有以下格式:
{
"id": 1,
"name": "wheelchair",
"description": "standard hospital wheelchair 18 x 16",
"condition": "like new",
"price": 100,
"pickup": true,
"shipping": true,
"category": "Wheelchairs & Scooters",
"photo": "https://cdn.fsastore.com/ProductImages/Large/423104_1.jpg",
"user": {
"id": 1,
"username": "anh",
"city": "Brooklyn",
"state": "NY",
"zip": 11218,
"email": "anh@anh.com"
}
}
- Note how the user associated with the item is nested within the item object. Serializer is the best thing since sliced bread, prove me wrong! 请注意与项目关联的用户如何嵌套在item对象内。 序列化器是切成薄片以来最好的东西,证明我错了!
步骤5.设置路线和操作 (Step 5. Set Up Route and Action)
I want to set up a route for items so that when I make a request to get
/items
, I receive JSON data representing the items I have in my database in the format just described. To do so, first specify inconfig/routes.rb
the following:我想为商品设置一条路线,以便在我请求获取
/items
,以刚才描述的格式接收代表数据库中商品的JSON数据。 为此,首先在config/routes.rb
指定以下内容:
resources :items, only: [:index]
Next, create the
items#index
action, which will look like:接下来,创建
items#index
操作,如下所示:
class ItemsController < ApplicationController
def index
items = Item.all
render json: items
end
end
Finally, fire up your rails server using
rails s
and navigate to http://localhost:3000/items on your browser to see your JSON data displayed.最后,使用
rails s
启动您的Rails服务器 并在浏览器上导航到http:// localhost:3000 / items以查看显示的JSON数据。
Okay, folks, that’s the gist of it! I hope this helps in easing your initial frustration regarding starting a Rails API. For more specific info on Rails, visit the official Rails documentation.
好的,伙计们,这就是要旨! 我希望这有助于减轻您对启动Rails API的最初沮丧。 有关Rails的更多具体信息,请访问正式的Rails文档 。
翻译自: https://medium.com/better-programming/how-to-fire-up-a-rails-api-for-your-new-project-6fad595caf07
rails api ws