简体   繁体   中英

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. 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'

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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