问题
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