簡體   English   中英

如何在單個控制器操作中創建多個新記錄?

[英]How do I create multiple new records in a single controller action?

我有一個學生資料頁面。 該頁面上有一個表格,您可以使用該表格為該學生創建新的Note記錄。 效果很好。

在此處輸入圖片說明

我想在標記為“誰?”的“注釋”文本字段上方添加一個新字段。 它允許您輸入其他學生,從而批量記錄筆記:

在此處輸入圖片說明

我不太確定如何構造表單和控制器動作,以實現與列出的每個學生相關的新Note記錄的批量創建。

我正在考慮采用這種方法:

POST到相同的操作( /notes#create ),並檢測params數組字段student_ids的存在,然后執行以下操作:

params[:student_ids].each do |s|
  note_params[:event_attributes][:student_id] = s
  note = Note.new(note_params)
  note.save
end

但是我必須修改note_params以便它在每次迭代中都包含適當的student_id參考。

當前,單數形式的note_params如下所示:

=> {
           "content" => "test",
  "event_attributes" => {
           "student_id" => "2",
               "user_id" => "1",
          "is_milestone" => "0",
    "happened_at_string" => ""
  }
}

有沒有更好/更干凈/更容易的方法來執行此操作,而不必循環遍歷每個id並手動修改參數?

您無需以這種方式修改參數。

params.fetch(:student_ids, []).each do |student_id|
  student = Student.find(student_id)
  note = student.notes.new(note_params)
  note.save
end

我認為您最好為此功能創建某種聯接表。

這樣,您可以創建一個注釋,然后通過簡單地復制聯接記錄來“復制”它。 不利的一面是,多個人都可以訪問一個便箋,但這沒關系:

#app/models/student.rb
class Student < ActiveRecord::Base
   has_many :created_notes, class_name: "Note", foreign_key: :user_id
   has_and_belongs_to_many :notes
end

#app/models/note.rb
class Note < ActiveRecord::Base
   belongs_to :user #-> to know who made it
   has_and_belongs_to :users
end

然后,您可以使用notes#create方法,如下所示:

#app/controllers/notes_controller.rb
class NotesController < ApplicationController
   def new
      @note  = current_user.created_notes.new
      @users = User.where.not(id: current_user.id)
   end

   def create
      @note = current_user.created_notes.new note_params
      @note.save
   end

   private

   def note_params
      params.require(:note).permit(:body, :user_ids)
   end
end

因此,您將能夠使用collection_select (或類似功能)功能來為您的note定義user_ids

#app/views/notes/new.html.erb
<%= form_for @note do |f| %>
   <%= f.collection_select :user_ids, @users, :id, :name %>
   <%= f.submit %>
<% end %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM