Rails 4 嵌套资源 3 个模型出错


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

当我添加指向选项的链接以获取该选项的所有注册show.html.erb时,就会发生这种情况。为了获取事件 id 和选项 id,我将以下内容添加到 OptionsController 中的 show 方法中:

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

这是我添加到show.html.erb文件的链接:

link_to "Registrations", event_option_registrations_path(@option)

这是我的 3 个模型的外观:事件、选项和注册

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

报名途径:

event_option_registrations_path /events/:event_id/options/:option_id/registrations(.:format) 注册#索引

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

此错误消息表示,当您执行此操作时,它找不到 id = nil 的选项:

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

这意味着,在这种情况下,您的params[:option_id] nil

您应该在控制器中放置一个 print 语句,如下所示:

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

然后,您将能够看到您在params哈希中得到的内容。然后,您可以获取正确的属性,然后完成其余的工作。希望这可以帮助您调试问题并解决问题。

更新

更改此内容:

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

自:

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

因为,在你的参数哈希中,你没有option_id键,但你有一个id键,它指的是option的 id。

最新更新