我很难用这个。我有一张专辑Model和一个Track Model,Track属于专辑和专辑有很多曲目。当我尝试创建一个带有曲目的专辑(下面的嵌套表格)时,它无法保存并重新播放“新曲目”。形成这条消息:
1错误禁止保存此专辑:曲目专辑必须 存在
相册控制器
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 你能帮我弄清楚究竟发生了什么吗?
答案 0 :(得分:3)
当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