在Rails 4

时间:2015-12-26 11:24:33

标签: ruby-on-rails associations

使用Rails 4。

# premedication.rb
class Premedication < ActiveRecord::Base
  has_many :premedication_dosages
  has_many :patients, through: :premedication_dosages
end

# patient.rb
class Patient < ActiveRecord::Base
  has_many :premedication_dosages
  has_many :premedications, through: :premedication_dosages
end

# premedication_dosage.rb
class PremedicationDosage < ActiveRecord::Base
  belongs_to :patient
  belongs_to :premedication
end

# patients_controller.rb
def patient_params
  params.require(:patient).permit(
    premedication_ids: [],
  )
end

# premedication_dosages join table
class CreatePremedicationDosage < ActiveRecord::Migration
  def change
    create_table :premedication_dosages do |t|
      t.belongs_to :patient, index: true
      t.belongs_to :premedication, index: true
      t.integer :dosage
    end
  end
end

# _form.html.erb
<%= form_for @patient do |f| %>
  <%= f.label :premedication %><br>
  <%= f.collection_check_boxes :premedication_ids, Premedication.all, :id, :name do |b| %>
    <div class="collection-check-box">
      <%= b.check_box %>
      <%= b.label %>
    </div>
  <% end %>
<% end %>

现在通过将premedication_idpatient_id存储在premedication_dosages表中,上面的工作正常,但premedication_dosages中有一个名为dosage的列,我想要存储一个值。我想在premedication_dosages表中得到的最终结果是:

premedication_id: 1
patient_id: 1
dosage: 10

如何将dosage的文本字段包含在表单中?

1 个答案:

答案 0 :(得分:0)

您需要使用accepts_nested_attributes_for

# patient.rb
class Patient < ActiveRecord::Base
  has_many :premedication_dosages
  has_many :premedications, through: :premedication_dosages

  accepts_nested_attributes_for :premedication_dosages
end


def patient_params
  params.require(:patient).permit(premedication_dosages_attributes: [:dosage, :premedication])
end

这意味着您必须更改表单结构:

#app/conntrollers/patients_controller.rb
class PatientsController < ApplicationController
   def new
      @premedication = Premedication.all
      @patient = Patient.new
      @patient.premedication_dosages.build
   end
end

<%= form_for @patient do |f| %>
  <%= f.fields_for :premedication_dosages do |d| %>
     <%= f.collection_select :premedication, @premedications, :id, :name %>
     <%= f.number_field :dosage %>
  <% end %>
  <%= f.submit %>
<% end %>

当然,这只允许您添加一个premedication_dosage,这意味着您必须使用Cocoon之类的内容来动态添加。

如果你愿意,我可以写cocoon,这需要一些时间,所以我会留下它,直到你告诉我上述是否是你需要的。