在为父分配ID之前保存嵌套数据

时间:2016-04-03 21:52:58

标签: javascript ruby-on-rails ruby ruby-on-rails-4

我有一个简历模型和一个教育模型。教育属于恢复和恢复has_many教育。 我目前正在使用Resume的show.html.erb视图中的表单输入教育数据,以确保其有效。

在我的routes.rb文件中,我有:

resources :resumes do
    resources :educations
end

在我的educations_controller.rb文件中,我有这个:

def create
    @resume = Resume.find(params[:resume_id])
    @education = @resume.educations.build(education_params)

    respond_to do |format|
      if @education.save
        format.html { redirect_to @resume, notice: 'Education was successfully created.' }
        format.json { render :show, status: :created, location: @education }
      else
        format.html { render :new }
        format.json { render json: @education.errors, status: :unprocessable_entity }
      end
    end
  end

这允许我在views/resumes/show.html.erb中拥有以下内容:

<%= form_for [@resume,Education.new] do |f| %>
  <div class="field">
    <%= f.label :sectionTitle %><br>
    <%= f.text_field :sectionTitle %>
  </div>
  <div class="field">
    <%= f.label :completed %><br>
    <%= f.date_select :completed %>
  </div>
  <div class="field">
    <%= f.label :degree %><br>
    <%= f.text_field :degree %>
  </div>
  <div class="field">
    <%= f.label :school %><br>
    <%= f.text_field :school %>
  </div>
  <div class="field">
    <%= f.label :summary %><br>
    <%= f.text_area :summary %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

目前正在运作,允许我按照简历输入多项教育。

问题是,我首先必须在创建教育条目之前创建简历条目,因为教育条目取决于resume_id整数。

如何重新构建我的代码,以便我可以为尚未拥有ID的特定简历创建多个教育条目,以便在提交简历时为其分配一个ID,然后将任何后续教育附加到给予resume_id并给出他们自己的教育ID?

我怀疑我可能不得不使用javascript这很好,但即便如此,我也不确定一旦拦截默认的表单动作该怎么做。

1 个答案:

答案 0 :(得分:0)

这只是一个小例子,但它完全正常。

在routes.rb

post 'add_resume_education' => 'resumes#twince'

在resumes_controller.rb中,在你的情况下。使用您自己的MODEL简历和教育,并改变传递参数。

def twince
     resume = Resume.create!(title: params[:data][:category_title])
     post = resume.educations.create!(sectionTitle: params[:data][:educations][:sectionTitle])
     redirect_to :back, notice: 'Yeah Created'
end
HTML页面中的

<%= form_for :data, url: add_resume_education_path do |f| %>

  <div class="field">
    <%= f.label :category_title %>
    <%= f.text_field :category_title %>
  </div>
<br>
  <div class="field">
    <%= f.fields_for :educations do |edu| %>
     <div class="field">
       <%= edu.label :sectionTitle %><br>
       <%= edu.text_field :sectionTitle %>
     </div>
    <% end %>
  </div>

    <br>
    <%= f.submit 'create' %>
<% end %>

这里还有很好的来源,Nested Form