如何通过关联使用has_many在模型上使用ActiveAdmin?

我在我的项目中使用ActiveAdmin的gem。

我有2个模型使用has_many通过关联。 数据库模式看起来和RailsGuide中的例子完全一样。 http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association has_many through association http://guides.rubyonrails.orghttp://img.dovov.comhas_many_through.png

我如何使用ActiveAdmin来…

  1. 显示每个病人在医生页面的预约date?
  2. 编辑医师页面中每个患者的预约date?

谢谢大家。 🙂

对于1)

show do panel "Patients" do table_for physician.appointments do column "name" do |appointment| appointment.patient.name end column :appointment_date end end end 

对于2)

 form do |f| f.inputs "Details" do # physician's fields f.input :name end f.has_many :appointments do |app_f| app_f.inputs "Appointments" do if !app_f.object.nil? # show the destroy checkbox only if it is an existing appointment # else, there's already dynamic JS to add / remove new appointments app_f.input :_destroy, :as => :boolean, :label => "Destroy?" end app_f.input :patient # it should automatically generate a drop-down select to choose from your existing patients app_f.input :appointment_date end end end 

在回答tomblomfield后续问题的评论中:

在您的AA ActiveAdmin.register Model do块中尝试以下操作:

  controller do def scoped_collection YourModel.includes(:add_your_includes_here) end end 

这应该延迟加载所有关联的每个索引页在一个单独的查询

HTH

它应该解决N + 1查询问题。

 show do panel "Patients" do patients = physician.patients.includes(:appointments) table_for patients do column :name column :appointment_date { |patient| patient.appointments.first.appointment_date } end end end 

这是我的工作(与select)

 permit_params category_ids: [] form do |f| inputs 'Shop' do input :category_ids, collection: Category.all.collect {|x| [x.name, x.id]}, as: :select, multiple: true, input_html: { class: "chosen-input", style: "width: 700px;"} end f.actions end 

@monfresh @tomblomfield你可以做

 has_many :appointments, ->{ includes(:patients) }, :through => :patients 

在医师模型中

…或者,我不确定你是否可以用formtastic来使用它,但是你可以用类似的东西来让范围可选

 has_many :appointments :through => :patients do def with_patients includes(:patients) end end 

appointment.patient病人不会n + 1了

如果您希望在面板行中显示多个字段,则可以使用以下视图:

 show do |phy| panel "Details" do attributes_table do ... # Other fields come here row :appointment_dates do apps="" phy.appointments.all.each do |app| apps += app.patient.name + ":" + app.appoinment_date + ", " end apps.chomp(", ") end end end end 

把它放在你的reditforms首先把appointment_ids允许列表:

 permit_params: appointment_ids:[] 

添加与表单有很多关系

 form do |f| f.has_many :appointments do |app| app.inputs "Appointments" do app.input :patients, :as => :select, :label => "Assigned Patients" app.input :appointment_date end end end 

应该工作,如果没有编码错误。