简体   繁体   English

我如何验证某些属性?

[英]How can i validate some attributes?

How can i validate if params have 'name' and 'section'?我如何验证参数是否具有“名称”和“部分”? for example: i want to validate 'name' but if there is not then i have to return 400, same with 'section'例如:我想验证“名称”,但如果没有,则我必须返回 400,与“部分”相同

 context 'validation' do
        let!(:params) do
          { article: {
            name: 'a1',
            section: 'A'
            ...
            color: 'red'
          } }
        end

i dont know how can i compare我不知道如何比较

it 'test, not allow empty name' do
   expect(name eq '').to have_http_status(400)
end

While you could check the parameters directly:虽然您可以直接检查参数:

def create
  if params[:article][:name].blank? || params[:article][:section].blank? 
     return head 400
  end 
 
  # ...
end

The Rails way of performing validation is through models: Rails 执行验证的方式是通过模型:

class Article < ApplicationRecord
  validates :name, :section, presence: true
end
class ArticlesController < ApplicationController
 
  # POST /articles
  def create
    @article = Article.new(article_params)
    if @article.save
      redirect_to @article, status: :created
    else
      # Yes 422 - not 400
      render :new, status: :unprocessable_entity
    end
  end

  private
 
  def article_params
    params.require(:article)
          .permit(:name, :section, :color)
  end
end
require 'rails_helper'
RSpec.describe "Articles API", type: :request do
  describe "POST /articles" do
    context "with invalid parameters" do
      it "returns 422 - Unprocessable entity" do
        post '/articles',
          params: { article: { name: '' }} 
        expect(response).to have_http_status :unproccessable_entity 
      end
    end
  end
end

This encapsulates the data together with validations that act on the data and validation errors so that you display it back to the user.这将数据与作用于数据的验证和验证错误一起封装,以便您将其显示回用户。

Models (or form objects) can even be used when the data isn't saved in the database.当数据未保存在数据库中时,甚至可以使用模型(或表单对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM