如何从动作中发布到表单

时间:2016-12-30 02:07:14

标签: ruby-on-rails

我有一个转到某个操作的链接,所以如果有人点击:

localhost/cart/checkout?pid=123

转到CartController结帐操作,然后显示表单。

但在某些情况下(取决于我使用id 123加载产品的时候)我可能不需要显示表单,我只需加载数据然后发布到表单的操作。

我如何以编程方式发布到我的表单将发布数据的位置。

class CartController < ApplicationController
  def checkout
    pid = params[:pid]
    product = Product.find(pid)
    if product....
       # no need to display view, just post to handleCheckout
    end
  end

  # checkout form posts to this action
  def handleCheckout
  end
end

1 个答案:

答案 0 :(得分:0)

我之前没有做过类似的事情,但我有一些想法,所以请注意,没有一个是经过测试的。

如果您的handleCheckout操作旨在用作Get请求,则可以使用参数重定向到此操作。像:

class CartController < ApplicationController
  def checkout
    pid = params[:pid]
    product = Product.find(pid)
    if product....
       redirect_to action: "handleCheckout", params: params
       # Not sure whether you will get it as 'params' or params[:params] in handleCheckout action
    end
  end

  # checkout form posts to this action
  def handleCheckout
  end
end

如果handleCheckout打算用作post,则上述方法可能无效,因为redirect_to会为该操作创建新的http Get请求。所以你可以尝试这样的事情:

def checkout
    pid = params[:pid]
    product = Product.find(pid)
    if product....
       handleCheckout
       # params since is a global hash and above method has access to it
    end
end

# checkout form posts to this action
def handleCheckout
   # your other code
   redirect_to 'some_action' and return
   # in above line you have to return with a render or redirect
   # Otherwise it will render 'checkout' template with render and redirect or
   # it will throw double render error if you have a simple render or redirect without explicit return
end

正如我所提到的,我没有尝试过任何上述代码。可能有错误。我希望它有所帮助。