简体   繁体   English

没有ID找不到[模型]:Rails 4自定义控制器操作

[英]Couldn't find [MODEL] without an Id : Rails 4 custom controller action

I'm trying to create a JSON feed for certain data to pull into a graph I have in a partial. 我正在尝试为某些数据创建JSON供稿,以将其放入部分包含的图形中。 I keep running into "Couldn't find Dam without an Id", and none of the answers on SO seem to have the fix. 我一直遇到“没有ID找不到水坝”的问题,SO的答案似乎都没有解决方法。 My params seem to be passing through fine, and I'm a bit perplexed. 我的参数似乎过得很好,我有些困惑。

routes.rb 的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

custom action in the dams_controller.rb: 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

I have tried using the id instead of the friendly.find , and get the same result. 我尝试使用id而不是friendly.find ,并得到相同的结果。 I have success if I delete the @dam line and manually add in a @dam.id to the @fish_counts instance. 如果删除@dam行并手动将@dam.id添加到@fish_counts实例,则可以@fish_counts

Why is the instance variable not picking up the parameters being passed to it? 为什么实例变量不接收传递给它的参数? And in situations like this, how would I debug? 在这种情况下,我该如何调试? raise params.inspect seems to have just shown me that the proper params are passing through. raise params.inspect似乎刚刚向我展示了正确的params正在通过。

Thanks 谢谢

edit 编辑

Here's the console output when I search w/o friendly.find: 这是当我搜索不使用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'

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM