从显示在 orders/new 视图和 orders/create 中访问 post id

Accessing post id from show in orders/new view and orders/create

我使用位于 orders/new 的 braintree api 结账。但是,我要向用户收取的价格是根据 post id 确定的。如果有帮助,用户将从 posts/show link 编辑到 orders/new。 提前致谢!

在 create 方法中访问 :post_id 有点棘手,因为没有 link 到创建视图来发送 :post_id with.

orders_controller 创建方法

def create
    post=Post.find(params[:post_id])
    nonce = params[:payment_method_nonce]
    render action: :new and return unless nonce
    result = Braintree::Transaction.sale(
    amount: post.price,
    payment_method_nonce: nonce
    )
  end
end

订购将用户发送到创建方法的新视图

<h2>Purchase Ticket (refresh if fields don't load)</h2>
<p>the price is <%= number_to_currency(@post.price) %></p>

<script src="https://js.braintreegateway.com/v2/braintree.js"></script>
<%= render 'payment/form' %>

使用我的表单的这个更新的顶部部分时

<%= form_tag orders_path, method: 'post' do %>
  <%= hidden_field :post_id, @post.id %>
  <div id="dropin"></div>
  <input type="submit" value="Pay">
<% end %>
<%= @params %>

您可以将 post_id 添加到指向 orders#new 操作的 post#show 视图的 link 中:

<%= link_to 'Purchase', new_order_path(post_id: @post.id) %>

在您的订单控制器中,您还需要允许 post_id 被强参数部分接受:

def post_params
  params.permit(:post_id)
end

我不知道你的 orders_params 方法中已经有什么,所以我给了你应该从 guides.

开始工作的最低限度

然后在 OrdersController 动作中你可以从参数中获取 post_id:

def new
  post_id = post_params[:post_id]
  # ...
end

更新: 扩展答案以包含额外的创建操作标准。

也许最直接的选择是在表单中添加一个隐藏字段来存储 post_id:

# app/views/payments/_form.html.erb
<%= form_tag orders_path, method: 'post' do %>
  <%= hidden_field_tag :post_id, @post.id %>
  <div id="dropin"></div>
  <input type="submit" value="Pay">
<% end %>

这意味着您在 post 上的 link_to 方法参数中输入的 post_id 将存储在表单中并提交给创建操作,您可以以同样的方式访问它:

class OrdersController < ApplicationController
  def new
    @post = Post.find(post_params[:post_id])
  end

  def create
    post = Post.find(post_params[:post_id])
    render text: post.price # to demonstrate
  end

  private
  def post_params
    params.permit(:post_id)
  end
end

我已经快速整理了一份 demo application 来展示工作代码。