如何从单独的控制器访问实例变量(结帐时的金额变量)

How to access an instance variable from a separate controller(amount variable in checkout)

我正在使用 Stripe 结帐处理我的工具租赁应用程序项目的结帐流程。当我想根据发布该工具的人想要租用它的价格动态更改租金时,我 运行 遇到了一个问题。

我的收费嵌套在我的工具中,如下所示:

Rails.application.routes.draw do
  devise_for :users

  root 'pages#home'

  resources :tools do
    resources :charges
    get :manage, :on => :collection
  end

当我导航到 /tools/1/charges/new 时出现以下错误:

Couldn't find Tool with 'id'=

这是我的收费控制器:

class ChargesController < ApplicationController

    def new
      @tool = Tool.find(params[:id])
      @amount = @tool.rent_price * 100
    end

    def create
      @tool = Tool.find(params[:id])
      @amount = @tool.rent_price * 100

      customer = Stripe::Customer.create(
        :email => 'example@stripe.com',
        :card  => params[:stripeToken]
      )

      charge = Stripe::Charge.create(
        :customer    => customer.id,
        :amount      => @amount,
        :description => 'Rails Stripe customer',
        :currency    => 'usd'
      )

    rescue Stripe::CardError => e
      flash[:error] = e.message
      redirect_to charges_path
    end

    private

    def tool_params
        params.require(:tool).permit(:name, :description, :user_id, :tool_image, :rent_price)
    end

end

这是我的工具控制器:

class ToolsController < ApplicationController
before_action :set_tool, only:[:show, :edit, :update, :destroy]
before_action :authenticate_user!, only:[:new, :destroy, :edit, :manage], notice: 'you must be logged in to proceed'

    def index
        @tools = Tool.all
    end

    def manage
        @user = current_user 
        @tools = @user.tools
    end

    def show
    end

    def new
        @tool = Tool.new 
    end

    def create
        @tool = Tool.new(tool_params)
        if @tool.save
            redirect_to @tool
        else
            redirect_to :action => "new"
            flash[:notice] = "You did not fill out all the fields"
        end
    end

    def edit
    end

    def update
        @tool.update(tool_params)
        redirect_to @tool
    end

    def destroy
        @tool.destroy
        redirect_to tools_path
    end

    private

    def set_tool
        @tool = Tool.find(params[:id])
    end

    def tool_params
        params.require(:tool).permit(:name, :description, :user_id, :tool_image, :rent_price)
    end

end

看看我的充电控制器。 Stripe 结帐文档通常将金额值硬编码到@amount 实例变量中。但是我希望它由工具创建者设置。我的工具 table 上有一个 rent_price 列,我想将此值传递给 amount 实例变量。

我试图通过找到创建费用的工具来做到这一点。但是,没有收费模型,因此工具和收费之间没有关联。 Stripe checkout 在没有模型的情况下工作。在这种情况下,我不确定如何访问收费控制器中工具创建者 (Tool.rent_price) 设置的金额。似乎没有 Tool.id 传递给参数。关于如何解决这个问题有什么想法吗?

我想我会创建一个收费模型,即使 stripe 没有说明并使用关联来链接调用金额。但不确定是否有更好的方法而无需创建收费模型。

对我来说,这似乎是使用错误参数的问题或路由问题。

您是否尝试过使用 Tool.find(params[:tool_id]) 而不是 Tool.find(params[:id])

根据有关嵌套资源的文档 http://guides.rubyonrails.org/routing.html#nested-resources,在您的示例中,params[:id] 应该与充电资源相关,params[:tool_id] 与工具资源相关。