【问题标题】:Trying to get variable from another controller with respond_to尝试使用 respond_to 从另一个控制器获取变量
【发布时间】:2020-01-20 21:34:01
【问题描述】:

我有一个名为 Orders 的控制器和另一个名为 Customers 的控制器。所以,在我的Order 上,我想保存我的customer 是谁。这两个模型有关联。

因此,在我的新订单视图中,我使用了一个表格,通过他的“cpf”(cpf 是我们在巴西用来识别公民身份的文件)来显示客​​户是谁,我这样做了:

<%= form_tag search_customer_path, method: :get do %>
  <%= text_field_tag :cpf, params[:cpf], placeholder: 'CPF' %>
  <%= button_tag type: :submit, class: "btn btn-primary" do %>
    <%= 'Selecionar' %>
  <% end%>
<% end%>

为了制作这个search_costumer_path 和制作checkout_path(我们稍后会用到),我把它改成routes.rb

get '/cart/checkout', to: 'orders#new', as: :checkout #-> This gives me the checkout_path
get 'search_customer', to: 'customers#search_customer'

在我的customers_controller.rb 上,我这样做了:

def search_customer
  @customer = Customer.find_by!(cpf: params[:cpf])
  respond_to do |format|
    format.html { redirect_to checkout_path } #-> @customer should be available in the checkout_path view, but it's not
  end
end

问题是当应用返回checkout_path时,@customernil

附加信息:为了尝试查找错误,我将customers_controllersearch_customer 操作替换为byebug,因此我可以在服务器上手动编码以查看参数是否正在传递并且变量是否正在设置,我没有问题。我得到了这样的东西:

Input> params
Return> <ActionController::Parameters {"cpf"=>"05864899995", "button"=>"", "controller"=>"customers", "action"=>"search_customer"} permitted: false>
Input> @customer = Customer.find_by(cpf: params[:cpf])
Return> #<Customer id: 2, name: "Thiago Fiorese", cpf: "05864899995", cel_phone: "83984572906", email: "thiagofiorese@gmail.com", address: "Rua Helena Meira Lima", neighborhood: "Tambaú", city: "João Pessoa", state: "PB", zipcode: "58039081", complement: "Apto 1001", reference: "Ao lado do Motiva", created_at: "2020-01-20 19:36:16", updated_at: "2020-01-20 19:36:16", number: "691">
Input> @customer.name
Return: "Thiago Fiorese"

所以...参数正在传递,并且变量理论上正在保存,因为我在 search_customer 操作中使用了相同的代码。我猜问题是使用respond_to 将该变量发送回结帐页面(订单控制器),因为当我被重定向回checkout_path 时,@customernil

如果您需要此信息:此应用是销售点,因此下订单的用户是店主或其员工,客户将无法访问该应用,但应保存在用于统计目的的顺序。

【问题讨论】:

    标签: ruby-on-rails ruby redirect model-view-controller


    【解决方案1】:

    您可以像这样将@customer.id 变量作为参数传递:

    respond_to do |format|
      format.html { redirect_to checkout_path(customer_id: @customer.id }
    end
    

    然后在你的 orders_controller 中

    def new
      @customer = Customer.find(params[:customer_id])
      ...
    end
    

    【讨论】:

    • 是的,成功了。非常感谢您帮助我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2019-03-31
    • 2020-11-23
    相关资源
    最近更新 更多