【发布时间】:2018-02-27 10:44:11
【问题描述】:
当涉及到嵌套参数和它们的控制器时,我似乎无法掌握路由的窍门。稍后编辑 - 路线看起来不错,但 parent_id 没有保存
在我的路线中
resources :galleries do
resources :album
end
然后在控制器中显示
def show
@albums = Album.find(params[:id])
@photos = @albums.photos.all
end
def index
@albums = Album.includes(:photos).all
end
def new
@gallery = Gallery.find(params[:gallery_id])
@album = @gallery.albums.build
@photos = @album.photos.build
end
def create
@gallery = Gallery.find(params[:gallery_id])
@album = @gallery.albums.new(album_params)
respond_to do |format|
if @album.save
params[:photos]['image'].each do |a|
@photo = @album.photos.create!(:image => a, :album_id => @album.id)
end
format.html { redirect_to gallery_path(@gallery.id), notice: 'Post was successfully created.' }
模型是这样的
class Album < ApplicationRecord
belongs_to :gallery
has_many :photos
accepts_nested_attributes_for :photos
end
class Gallery < ApplicationRecord
has_many :albums
accepts_nested_attributes_for :albums
end
在我的画廊表单中,我可以看到所有画廊列的值。 现在我正在尝试为初学者显示这样的专辑列表,但没有任何显示:
<% @gallery.albums.each do |album| %>
<%= album.name %>
<%= link_to "Destroy", album, method: :delete %>
<% end %>
原来我新建相册的时候没有保存画廊的parent_id
我这样称呼专辑创作
<%= link_to 'New Album', new_gallery_album_path(@galleries.id) %>
导致这个网址http://localhost:3000/galleries/1/albums
我不确定创建定义中缺少什么以便在我保存相册时保存 gallery_id
稍后编辑
在应用@Esther 的建议之前进行控制台
Gallery Load (1.0ms) SELECT "galleries".* FROM "galleries" WHERE "画廊"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]] (0.0ms) BEGIN SQL (0.0ms) INSERT INTO "albums" ("band", "gallery_id", "created_at", "updated_at") 值 ($1, $2, $3, $4) 返回 "id" [["ban d", "test"], ["gallery_id", 1], ["created_at", "2017-09-18 21:09:59.805397"], ["updated_at", "2017-09-18 21:09:59.805397"]]
(0.0ms) 提交 (0.0ms) 开始
并且在修改控制器后使用@gallery.albums.create(album_params)而不是@gallery.albums.create
Gallery Load (0.0ms) SELECT "galleries".* FROM "galleries" WHERE "画廊"."id" = $1 限制 $2 [["id", 1], ["LIMIT", 1]] (0.0ms) 开始 SQL (1.0ms) INSERT INTO "albums" ("band", "gallery_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) 返回 "id" [[“禁止 d", "new"], ["gallery_id", 1], ["created_at", "2017-09-19 18:28:41.093138"], ["updated_at", "2017-09-19 18:28: 41.093138"]] (0.0ms) 提交 (0.0ms) 开始 (1.0ms) 提交 (0.0ms) 开始
【问题讨论】:
标签: ruby-on-rails controller nested-forms