Emily
Emily

Reputation: 164

Rails 5 Nested form, parent doesn't saved

I have hard time with this one. I have an album Model and a Track Model, Track belongs to album and album has many tracks. When I try to create an album with a track(the nested form below) it fails to save and renser the 'new' form with this message:

1 error prohibited this album from being saved: Tracks album must exist

Albums Controller

class Admin::AlbumsController < AdminController    
  def new
    @album = Album.new
    @album.tracks.build
  end

  def create
    @album = Album.new(album_params)

    if @album.save
        redirect_to admin_album_path(@album)
    else
        render 'new'
    end
  end

  private

    def album_params
        params.require(:album).permit(:title, :kind, :release, tracks_attributes: [:id, :title, :time, :order])
    end
end

Album Model

class Album < ApplicationRecord
    has_many :tracks
    accepts_nested_attributes_for :tracks
end

Track Model

class Track < ApplicationRecord
    belongs_to :album
end

Form

<%= form_for [:admin, @album] do |f| %>

    <% if @album.errors.any? %>
        <div id="error_explanation">
            <h2>
                <%= pluralize(@album.errors.count, "error") %> prohibited this album from being saved:
            </h2>
            <ul>
                <% @album.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
                <% end %>
            </ul>
        </div>
    <% end %>

    <h5>Album</h5>
    <p>
        <%= f.label :title %><br>
        <%= f.text_field :title %>
    </p>

    <p>
        <%= f.label :kind %><br>
        <%= f.text_field :kind %>
    </p>

    <p>
        <%= f.label :release %><br>
        <%= f.text_field :release %>
    </p>
    <br><br><br>

    <h5>Track</h5>
    <%= f.fields_for :tracks do |tracks_form| %>
        <p>
            <%= tracks_form.label :title %>
            <%= tracks_form.text_field :title %>
        </p>
        <p>
            <%= tracks_form.label :time %>
            <%= tracks_form.text_field :time %>
        </p>
        <p>
            <%= tracks_form.label :order %>
            <%= tracks_form.text_field :order %>
        </p>
    <% end %>

    <%= f.submit class: "waves-effect waves-light btn" %>

<% end %>

I think album doesn’t saved so track can’t get the album id.
Could you help me to figure out what really happens?

Upvotes: 1

Views: 257

Answers (1)

Panos Angel
Panos Angel

Reputation: 136

When Rails attempts to save the track, the album has not yet been committed into the database. In order for this to to work you need to have the :inverse_of

Try this

class Album < ApplicationRecord
    has_many :tracks, inverse_of: :album
    accepts_nested_attributes_for :tracks
end

class Track < ApplicationRecord
    belongs_to :album, inverse_of: :tracks
    validates_presence_of :album
end

Upvotes: 3

Related Questions