【问题标题】:Rails: Couldn't find nested resource with IDRails:找不到具有 ID 的嵌套资源
【发布时间】:2017-09-17 20:24:19
【问题描述】:

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

当我尝试从这里添加新专辑时 http://localhost:3000/galleries/1/albums/new 我得到了

“ActiveRecord::RecordNotFound in AlbumsController#create 不能 查找带有 '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

为了进入创建相册的页面,我在画廊的“显示”页面中这样称呼它 这会导致正确的页面在链接中确实具有库的 ID 1

但在控制器中,我真的不明白为什么gallery_id 被处理为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|

...

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

【问题讨论】:

    标签: ruby-on-rails nested-forms


    【解决方案1】:

    我问了之后才知道。在表格中,我只是在打电话

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

    但是改成之后

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

    成功了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多