[英]Rails form action and routes
I have a controller action that requires parameters, and has to be accessed both through get and post. 我有一个需要参数的控制器操作,必须同时通过get和post访问。 with get it looks like: 有了它看起来像:
get 'cart/add:id,:qty' => 'cart#add', as: :addToCart
the controller action is: 控制器动作是:
def add
product = Product.find(params[:id])
if ::AddToCart.new(@cart, product, params[:qty]).execute
flash[:succes] = "Product(s) added."
else
flash[:failure] = "Product cannot be added."
end
redirect_to request.referer
end
how should the post route look like if i would like it to use the same action. 如果我希望它使用相同的操作,发布路线应该如何?
PS: i use the get version as a link_to when only one product is added, the post route is needed because the quantity will be unknown PS:当仅添加一种产品时,我将获取版本用作link_to,因此需要发布路线,因为数量未知
You should make this strictly a post route. 您应严格将其设为发布路线。 If you want, you can default the quantity to one when it isn't provided. 如果需要,可以在未提供数量时将其默认设置为1。 Or, use ajax to post to the route with a quantity of one when they click the "add one" link. 或者,当他们单击“添加一个”链接时,使用ajax发布数量为1的路由。 That way it can look and seem to behave like a regular link_to sort of link, but you'll still have the benefits of only updating data via POST and leaving all your actual GET requests idempotent. 这样,它看起来和看起来像是常规的link_to链接,但是您仍然可以享受到仅通过POST更新数据并保持所有实际GET请求完全幂等的好处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.