I can't seem to get the hang of routes when it comes to nested parameters and the controllers for them. Later edit - routes seemed fine, but parent_id is not saved
In my routes I have
resources :galleries do
resources :album
end
Then show in controller
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.' }
Models are like this
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
In my form for galleries, I see fine all galleries column values. Now I am trying to display a list of its albums like this for starters, but nothing shows up:
<% @gallery.albums.each do |album| %>
<%= album.name %>
<%= link_to "Destroy", album, method: :delete %>
<% end %>
It turns out that the parent_id of the gallery is not being saved when I create a new album
I call the album creation like this
<%= link_to 'New Album', new_gallery_album_path(@galleries.id) %>
which leads to this url http://localhost:3000/galleries/1/albums
I am not exactly sure what is missing from the create definition in order for the gallery_id to be saved when I save the album
Later edit
Console before applying @Esther's suggestion
Gallery Load (1.0ms) SELECT "galleries".* FROM "galleries" WHERE "galleries"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]] (0.0ms) BEGIN SQL (0.0ms) INSERT INTO "albums" ("band", "gallery_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "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) COMMIT (0.0ms) BEGIN
And after modifying the controller to use @gallery.albums.create(album_params)
instead of @gallery.albums.create
Gallery Load (0.0ms) SELECT "galleries".* FROM "galleries" WHERE "galleries"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]] (0.0ms) BEGIN SQL (1.0ms) INSERT INTO "albums" ("band", "gallery_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["ban 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) COMMIT (0.0ms) BEGIN (1.0ms) COMMIT (0.0ms) BEGIN