Ruby on rails 在Rails 4的联接表中保存其他属性
使用Rails 4Ruby on rails 在Rails 4的联接表中保存其他属性,ruby-on-rails,associations,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
# 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 %>
表单中应如何包含剂量的文本字段?您需要使用:
#patient.rb
类Patient
这意味着您必须更改表单结构:
#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 %>
#app/conntrollers/patients_controller.rb
类PatientsController<应用程序控制器
def新
@术前用药=术前用药
@病人
@患者.术前用药\剂量.构建
结束
结束
当然,这只允许您添加单个预用药剂量
,这意味着您必须使用类似的方法来更动态地添加
如果你愿意,我可以写cocoon
,这需要一些时间,所以我会留下它,直到你告诉我上面的内容是否是你需要的。谢谢@Rich Peck,但我需要它是一个复选框,可以是多个选择,每个选择都接受剂量
值(如果选择)。
# 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 %>