【问题标题】:Couldn't find [MODEL] without an Id : Rails 4 custom controller action找不到没有 ID 的 [MODEL]:Rails 4 自定义控制器操作
【发布时间】:2015-08-16 01:03:45
【问题描述】:

我正在尝试为某些数据创建一个 JSON 提要,以将其拉入我的部分图表中。我一直遇到“找不到没有 ID 的大坝”,而关于 SO 的答案似乎都没有解决方法。我的参数似乎很好,我有点困惑。

routes.rb

require "resque/server"
Rails.application.routes.draw do
  mount Resque::Server, :at => "/resque"

  root 'home#index'
  get 'about', to: 'home#about'

  resources :dams, only: [:index, :show] do
      get 'count_data', to: 'dams#count_data'
    resources :fish_counts, only: [:index, :show]
  end

  resources :fish
end

dams_controller.rb 中的自定义操作:

    def count_data
      @dam = Dam.includes(:fish_counts, :fish).friendly.find(params[:id])
      @fish_counts = FishCount.for_year(Date.today.year).where("dam_id =?",  @dam.id).limit(200).order(count_date: :desc)
      respond_to do |format|
        format.json {
          render json: {:fish_counts => @fish_counts}
        }
      end
  end

我尝试使用 id 而不是 friendly.find,并得到相同的结果。如果我删除@dam 行并手动将@dam.id 添加到@fish_countsinstance,我就成功了。

为什么实例变量没有获取传递给它的参数?在这种情况下,我将如何调试? raise params.inspect 似乎刚刚向我展示了正确的参数正在通过。

谢谢

编辑

这是我搜索 w/o friendly.find 时的控制台输出:

Started GET "/dams/3/count_data.json" for ::1 at 2015-08-15 18:11:04 -0700
Processing by DamsController#count_data as JSON
Parameters: {"dam_id"=>"3"}
Completed 404 Not Found in 2ms (ActiveRecord: 0.0ms)

ActiveRecord::RecordNotFound (Couldn't find Dam without an ID):
app/controllers/dams_controller.rb:15:in `count_data'

【问题讨论】:

    标签: ruby-on-rails ajax ruby-on-rails-4 rails-routing friendly-id


    【解决方案1】:

    您在堆栈跟踪中看到 params 中没有 :id,而是 :dam_id,因此您应该像这样使用它:

    @dam = Dam.includes(:fish_counts, :fish).find(params[:dam_id])
    

    【讨论】:

    • 我正盯着它看,它刚刚击中我,回来回答我自己的问题,看看你说对了。谢谢!会接受。
    猜你喜欢
    • 2020-05-18
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多