【发布时间】:2016-09-04 04:42:41
【问题描述】:
我正在使用 has_nested_attributes_for 创建两个不同模型(父级和子级)的两条记录。目前使用 has_nested_attributes,我在父级上的 new.html.erb 表单成功创建了父级和子级并将它们关联在一起。但是,父记录可以拥有_many 个与之关联的子模型。因此,从新表单中,我需要能够输入 url 属性(父模型上的列),如果 url 已经存在......它应该作为已经存在的 Parent 弹出(我可以使用'rails-jquery -如果需要 jquery,则为此自动完成'gem)...从而在表单上设置现有的父 ID。但是,如果它尚不存在,则该表单应创建一个新的父记录和子记录,就像当前成功发生的那样。
我需要如何更改我的控制器和视图来完成这种条件嵌套表单?谢谢,
父控制器:
class StoriesController < ApplicationController
def new
@story = Story.new
video = @story.videos.build
end
def create
@story = Story.new(story_params)
if @story.save
flash[:success] = "Your story video has been created."
redirect_to current_narrator
else
flash[:alert] = "Your story or video could not be saved. Please include all fields."
render 'new'
end
end
private
def story_params
params.require(:story).permit(:headline, :url, videos_attributes: [
:imovie,
:director_id
],)
end
end
应用程序/视图/故事 new.html.erb:
<!-- New Story Nested Form -->
<% provide(:title, 'New Story') %>
<div class="container s-in-reg">
<div class="authform">
<h1>New Story</h1>
<%= form_for @story do |f| %>
<div class="field">
<%= f.label :headline %><br />
<%= f.text_field :headline %>
</div><br/>
<div class="field">
<%= f.label :url %><br />
<%= f.text_field :url %>
</div><br/>
<%= f.fields_for :videos do |builder| %>
<div class="field">
<%= render 'video_fields', f: builder %>
# Video_fields partial contains the nested video fields required
</div>
<% end %>
<%= f.submit "Post this story", class: "btn btn btn-info" %>
<% end %>
</div>
</div>
Story.RB 模型:
has_many :videos
accepts_nested_attributes_for :videos
validates :headline, presence: true
validates :url, presence: true, uniqueness: true
Video.RB 模型:
class Video < ActiveRecord::Base
belongs_to :story
belongs_to :user
has_attached_file :mpeg
has_nested_attributes_for :story
end
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 parent-child jquery-ui-autocomplete nested-attributes