簡體   English   中英

如何允許和驗證 ruby 中的參數?

[英]how to permit and validate parameter in ruby?

我正在驗證 ruby 控制器/模型中傳遞的參數,如下所示。 在 controller 中,我只想允許允許 id 和 name 參數。 我想將該 id 和 name 參數傳遞給 model class 並驗證它們是否具有可接受的值。 我有追隨者,這是在 ruby 中可接受的方式嗎?

controller class

class PersonController 
  def create
    Person.find_By_person_id(check_params[:id], check_params[:name])
  end

  ...

  private

    def check_params
      params.permit(:id, :name)
    end
end

model class

class People
 class<<self
   def find_By_person_id(id, name)
      //validate id and name have values
      raise ArugmentError unless validate_params

      //calls another service to get the person

   end

   private
   def validate_params
      return false if id is not integer || id is less than zero || name is empty string 
   end 
 end
end

您應該考慮使用 Active Record Validations ( https://guides.rubyonrails.org/active_record_validations.html ) 並檢查是否存在:id:name 您的 model 將如下所示:

人.rb

class People < ApplicationRecord
  validates :name, presence: true
end

至於 id,Active Record 會為要創建的任何新記錄生成一個唯一的運行 id,因此我認為您沒有任何理由需要驗證它 - 除非您從前端傳遞另一個:id ,其中如果你應該重命名它,這樣它就不會與記錄的:id沖突。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM