Rails: Couldn't find nested resource with ID

人走茶凉 提交于 2019-12-11 05:53:17

问题


I have a 3 layers nested model: galleries -> has many albums -> has many photos

When I try to add a new album from here http://localhost:3000/galleries/1/albums/new I am getting

"ActiveRecord::RecordNotFound in AlbumsController#create Couldn't find Gallery with 'id'="

Albums model:

class Album < ApplicationRecord
 belongs_to :gallery
 has_many :photos
  accepts_nested_attributes_for :photos

Gallery model

   class Gallery < ApplicationRecord
   has_many :albums
  accepts_nested_attributes_for :albums
 end

Routes

....
 resources :galleries do
  resources :albums 
 end
resources :photos, only: [:index, :new, :create, :destroy]
 resources :photos, only: [:index]
 resources :albums  do
   resources :photos, :controller => "albums"
 end

In order to get to the page to create album, I call it like this from within the Show page for the gallery <%= link_to 'New Album', new_gallery_album_path(@galleries.id) %> This leads to the correct page which does have the ID 1 of the gallery in the link

But in the controller, I don't really understand why the gallery_id is hanlded as a nil

  def new
   @gallery = Gallery.find(params[:gallery_id])
   @album = Album.new
   @photos = @album.photos.build
  end
 def create
  @gallery = Gallery.find(params[:gallery_id])
  @album = Album.new(album_params)

  respond_to do |format|

...

I can paste the rest of the controller, but now the error is pointing at the line in the create function @gallery = Gallery.find(params[:gallery_id]) Why does this work ok within the NEW but not for the create?


回答1:


Actually figured it out after I asked. In the form, I was only calling

  %= form_for @album], :html => { :mutiplart...

But after changing it to

  <%= form_for [@gallery,@album], :html => { :mu

It worked



来源:https://stackoverflow.com/questions/46268538/rails-couldnt-find-nested-resource-with-id

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