【问题标题】:How do I pass an object in the rails URL helper如何在 rails URL helper 中传递对象
【发布时间】:2022-01-23 19:27:38
【问题描述】:

我在理解如何在 rails 中设置路由以将对象传递到 URL 帮助程序时遇到问题。

我添加了一个新方法add_item

  def add_item
    @item = Item.create(item_params)
    puts @hospital.inspect
    puts @item.inspect
    @hospital.items << @item

    respond_to do |format|
      if @hospital.save
        format.html { redirect_to hospital_url(@hospital), notice: "Item was added to hospital" }
        format.json { render :show, status: :ok, location: @hospital }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @hospital.errors, status: :unprocessable_entity }
      end
    end
  end

我添加了对应的路线

  resources :hospitals do
    member do
      post :add_item
    end
  end

但是当我运行我的测试时使用

      post add_item_hospital_url(@hospital), params: { item: { item_code: item.item_code, description: item.description, gross_charge: item.gross_charge } }

测试中的@hospital 不是nil,但在控制器上是。我究竟做错了什么? 我的路线似乎没问题。

add_item_hospital POST   /hospitals/:id/add_item(.:format)

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    实例变量@hospital在控制器中是nil,因为它没有被设置。也许你可以添加一个before_action 来设置实例变量的值,或者只是将它添加到add_item 方法中。

    将模型传递给 URL 帮助程序时,可以在 params 哈希中找到该对象的 id

    class HospitalsController < ApplicationController
      before_action :set_hospital, only: :add_item
      
      def add_item
        # ... your code here
      end
    
      private
        def set_hospital
          @hospital = Hospital.find(params[:id])
        rescue ActiveRecord::RecordNotFound
          # handle exception
        end
    end
    

    【讨论】:

    • 我明白了!那么,当您使用 URL 助手并将 @var 传递给它时,它是如何工作的呢?我看到他们在更新和其他方法上这样做。
    • 似乎在您的测试文件中,您在代码中的某处定义了@hospital,这就是它起作用的原因,但是控制器对测试的实例变量一无所知,这就是为什么您必须从:id 参数重新设置
    • 啊!我懂了!因此,当我们将它传递给 URL 助手时,可以在参数中找到该 obj 的 id。谢谢!
    猜你喜欢
    • 2011-02-24
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多