rails 重定向中的条件验证
conditional validation in rails redirect
实现邮政编码验证功能的最佳方式是什么。我不是在谈论邮政编码的格式,而是在验证用户输入的邮政编码是您开展业务的邮政编码。此处示例:https://doughbies.co/
例如:我只送货到邮政编码 12345,所以如果用户输入不同的邮政编码,他会收到一条失败消息说 "we do not deliver to your area",但如果用户输入 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
以及在controller中如何使用,以创建订单为例:
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
实现邮政编码验证功能的最佳方式是什么。我不是在谈论邮政编码的格式,而是在验证用户输入的邮政编码是您开展业务的邮政编码。此处示例:https://doughbies.co/
例如:我只送货到邮政编码 12345,所以如果用户输入不同的邮政编码,他会收到一条失败消息说 "we do not deliver to your area",但如果用户输入 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
以及在controller中如何使用,以创建订单为例:
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