[英]conditional validation in rails redirect
什么是實現郵政編碼驗證功能的最佳方式。 我不是在談論郵政編碼的格式,而是驗證用戶輸入的郵政編碼是你做生意的。例如: https : //doughbies.co/
例如:我只發送到郵政編碼12345,因此如果用戶輸入不同的郵政編碼,他會收到一條失敗消息,說“我們沒有送到您的地區”,但如果用戶輸入12345,則會被重定向到商店。
我正在考慮生成一個郵政編碼模型,其中可接受的郵政編碼作為數組中的常量。 然后創建一個可交付成果? 將用戶輸入與數組常量中的一個郵政編碼匹配的函數。 只是不知道我可以使用哪些方法或驗證。
你有模型來代表訂單嗎? 如果是這樣,您可以在那里進行驗證,而無需單獨的模型。
class Order < ActiveRecord::Base
SHIPPABLE_ZIPS = ['12345']
validate :zip_shippable
def zip_shippable
errors.add(:zip, "cannot be shipped to") unless SHIPPABLE_ZIPS.include?(zip)
end
end
有關如何在控制器中使用它,請創建一個訂單作為示例:
class OrdersController < ActionController::Base
def create
@order = Order.new(order_params) # "order_params" is params from the form
if @order.save
redirect orders_path # redirect the user to another page
else
render :new # render the form again, this time @order would contain the error message on zip code
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.