首页 > 解决方案 > Rails form_for 具有相同属性的嵌套和关联资源已填充文本

问题描述

我正在为两个关联模型播放列表和视频创建一个嵌套表单,它们也是嵌套资源,我正在尝试创建一个嵌套表单。每个播放列表都有许多视频,每个视频属于一个播放列表。它们都具有标题和描述的属性。转到 new_playlist_video_path 会导致将播放列表的标题和描述放入视频的表单字段中。

** 更新 ** 当我访问 new_playlist_video_path(playlist) 时,视频表单呈现,但控制器认为我在 playlist#update 中并向播放列表路径发送补丁请求。

路线

 resources :playlists do
    resources :videos
  end

我的控制器

before_action :set_playlist, only: %i[new edit update create]

 # GET /videos/new
  def new
    @video = @playlist.videos.build
  end

  private


  def set_playlist
    @playlist = Playlist.find(params[:playlist_id])
  end

视频#new

<%= form_for([@video, @playlist], url: playlist_videos_path, class: "contents") do |form| %>
  <% if @video.errors.any? %>
    <div id="error_explanation" class="bg-red-50 text-red-500 px-3 py-2 font-medium rounded-lg mt-3">
      <h2><%= pluralize(@video.errors.count, "error") %> prohibited this video from being saved:</h2>

      <ul>
        <% @video.errors.each do |error| %>
          <li><%= error.full_message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="my-5">
    <%= form.label :title %>
    <%= form.text_field :title, class: "block shadow rounded-md border border-gray-200 outline-none px-3 py-2 mt-2 w-full" %>
  </div>

  <div class="my-5">
    <%= form.label :description %>
    <%= form.text_area :description,  text: nil , rows: 4, class: "block shadow rounded-md border border-gray-200 outline-none px-3 py-2 mt-2 w-full" %>
  </div>

  <div class="inline">
    <%= form.submit class: "rounded-lg py-3 px-5 bg-blue-600 text-white inline-block font-medium" %>
  </div>
<% end %>

我可以更改视频的属性,但这似乎工作量太大,因为我必须重新编写验证、测试和大量 HTML。如何让我的视频表单不显示其所属模型的标题和描述?

标签: ruby-on-railsrubyformsassociations

解决方案


My form was wrong, It should have been


<%= form_for([@playlist, @video, ], class: "contents") do |form| %>
~~~ form contents 

推荐阅读