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_counts
instance.
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'
You see in the stack trace that there is no :id in params, but :dam_id, so you should use it like this :