Asan
Asan

Reputation: 151

Rails 4 Nested Resources Error with 3 models

Error: ActiveRecord::RecordNotFound Couldn't find Option with 'id'=

This is happening when I add a link to the options show.html.erb to get all the registrations for that option. In order to get the event id and the option id, I'm adding the following to the show method in the OptionsController:

@event = Event.find(params[:event_id])
@option = Option.find(params[:option_id])

This is the link I'm adding to the show.html.erb file:

link_to "Registrations", event_option_registrations_path(@option)

This is how my 3 models look: Event, option and registrations

event.rb:

class Event < ActiveRecord::Base
    has_many :options, dependent: :destroy
end

option.rb:

class Option < ActiveRecord::Base
  belongs_to :event
  has_many :registrations
end

routes.rb:

  resources :events do
    resources :options do
      resources :registrations
    end

Route for Registrations:

event_option_registrations_path /events/:event_id/options/:option_id/registrations(.:format) registrations#index

Upvotes: 1

Views: 83

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

Error: ActiveRecord::RecordNotFound Couldn't find Option with 'id'=

This error message is saying that, it can't find the option with id = nil when you do this:

@option = Option.find(params[:option_id])

which means, your params[:option_id] is nil in this case.

You should put a print statement in your controller like this:

def your_action
  # these are for debugging
  puts params.inspect
  puts params[:option_id]
  @event = Event.find(params[:event_id])
  @option = Option.find(params[:option_id])
end

Then you will be able to see what you are getting inside your params hash. Then, you can grab the correct attribute and then do the rest of the work. Hope this helps you debug the issue and solve your problem.

Update

change this:

@option = Option.find(params[:option_id])

To:

@option = Option.find(params[:id])

Because, in your params hash, you don't have a option_id key, but you have a id key which refers to the id of the option.

Upvotes: 1

Related Questions