Rails 5 嵌套表单,父级不保存

Rails 5 Nested form, parent doesn't saved

我很难接受这个。我有一个专辑模型和一个曲目模型,曲目属于专辑,专辑有很多曲目。当我尝试用曲目(下面的嵌套形式)创建专辑时,它无法保存和重新生成 'new' 形式,并显示以下消息:

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

专辑控制器

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

专辑型号

class Album < ApplicationRecord
    has_many :tracks
    accepts_nested_attributes_for :tracks
end

赛道模型

class Track < ApplicationRecord
    belongs_to :album
end

形式

<%= 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 %>

我认为专辑没有保存,所以曲目无法获取专辑ID。
你能帮我弄清楚到底发生了什么吗?

当 Rails 尝试保存曲目时,专辑尚未提交到数据库中。为了让这个工作你需要有 :inverse_of

试试这个

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