Rails:找不到ID为的嵌套资源 [英] Rails: Couldn't find nested resource with ID

查看:72
本文介绍了Rails:找不到ID为的嵌套资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3层嵌套模型: 画廊->有很多相册->有很多照片

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

当我尝试从此处添加新专辑时 http://localhost:3000/galleries/1/相册/新 我得到了

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

"AllowsController#create中的ActiveRecord :: RecordNotFound无法 查找带有'id'="

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

相册模型:

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

画廊模型

   class Gallery < ApplicationRecord
   has_many :albums
  accepts_nested_attributes_for :albums
 end

路线

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

为了进入创建相册的页面,我在画廊的显示"页面中这样称呼它 <%= link_to'New Album',new_gallery_album_path(@ galleries.id)%> 这会导致在链接中确实具有画廊ID 1的正确页面

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

但是在控制器中,我不太明白为什么把gallery_id设置为nil

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|

...

我可以粘贴控制器的其余部分,但是现在错误指向了create函数中的那一行 @gallery = Gallery.find(params [:gallery_id]) 为什么在NEW内可以正常工作,而在创建内却不能正常工作?

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?

推荐答案

我问过之后,实际上就知道了.在表格中,我只是打电话给

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

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

但是将其更改为

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

有效

这篇关于Rails:找不到ID为的嵌套资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆