【问题标题】:Rails 5 Nested form, parent doesn't savedRails 5嵌套表单,父级不保存
【发布时间】:2016-10-03 14:52:24
【问题描述】:

我很难用这个。我有一个专辑模型和一个曲目模型,曲目属于专辑,专辑有很多曲目。当我尝试创建带有曲目的专辑(下面的嵌套表单)时,它无法保存并显示此消息的“新”表单:

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。
你能帮我弄清楚到底发生了什么吗?

【问题讨论】:

  • 您无法在尚未持久化的对象上建立关系。您会注意到在此之前没有在数据库中为对象分配 ID!因此,您必须创建专辑,然后您可以通过 album.tracks.new(params here) 将曲目与其关联
  • 您在控制台中尝试过同样的方法吗?你能展示这个模型的迁移吗?

标签: ruby-on-rails nested-forms ruby-on-rails-5


【解决方案1】:

当 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    相关资源
    最近更新 更多