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

落爺英雄遲暮 提交于 2019-12-11 03:23:59

问题


I'm trying to create a JSON feed for certain data to pull into a graph I have in a partial. I keep running into "Couldn't find Dam without an Id", and none of the answers on SO seem to have the fix. My params seem to be passing through fine, and I'm a bit perplexed.

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:

    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. I have success if I delete the @dam line and manually add in a @dam.id to the @fish_countsinstance.

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.

Thanks

edit

Here's the console output when I search 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'

回答1:


You see in the stack trace that there is no :id in params, but :dam_id, so you should use it like this :

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


来源:https://stackoverflow.com/questions/32030893/couldnt-find-model-without-an-id-rails-4-custom-controller-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!