rails api ws_如何为新项目启动Rails API

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

步骤1.启用“ bcrypt”和“ rack-cors” (Step 1. Enable ‘bcrypt’ and ‘rack-cors’)

  • Navigate into your Gemfile, uncomment out gem ‘bcrypt’ and gem ‘rack-cors’.

    导航到您的Gemfile ,取消注释Gemfile gem 'bcrypt'gem 'rack-cors'

  • The bcrypt gem allows you to use the has_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 the Rack::Cors configuration, and change origins from 'example.com' to '*':

    导航到config/initializers/cors.rb ,取消注释Rack::Cors配置,并将源从'example.com'更改为'*'

Image for post
  • 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 and items. This is what I want them to look like:

    我的数据库将保存两个表的信息: usersitems 。 这就是我希望他们看起来像的样子:

Image for post
  • 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 for user_id in your items table. Additionally, we use column name password_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 and rails 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_manybelongs_to )。

第3步。使用“ bcrypt”并添加一些验证 (Step 3. Put ‘bcrypt’ to Use and Add Some Validations)

  • The bcrypt gem you installed allows you to use a macro called has_secure_password. Add this to your User model since we will be validating the user’s password. While you’re there, add validations for email and username:

    您安装的bcrypt gem允许您使用名为has_secure_password的宏。 将此添加到您的用户模型,因为我们将验证用户密码。 在那里,添加对emailusername验证:

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 in rails 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, add gem 'active_model_serializers' to your Gemfile and again run bundle 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 Userrails 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. My UserSerializer 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, and password_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_atupdated_atpassword_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 in config/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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值