Ruby on rails rails重定向中的条件验证
实现邮政编码验证功能的最佳方式是什么。我不是说邮政编码的格式,而是验证用户输入的邮政编码是否是您从事业务的邮政编码。示例如下: 例如:我只发送到邮政编码12345,所以如果用户输入不同的邮政编码,他会收到一条失败消息,说“我们不发送到您的地区”,但如果用户输入12345,他会被重定向到商店Ruby on rails rails重定向中的条件验证,ruby-on-rails,ruby,forms,validation,Ruby On Rails,Ruby,Forms,Validation,实现邮政编码验证功能的最佳方式是什么。我不是说邮政编码的格式,而是验证用户输入的邮政编码是否是您从事业务的邮政编码。示例如下: 例如:我只发送到邮政编码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
类OrdersControllervalidates:zipcode,:inclusion=>{:in=>@allowed\u zip\u codes}
谢谢。