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

Vic*_*Lam 53 rubygems ruby-on-rails associations ruby-on-rails-3 activeadmin

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

我有2个模型使用has_many通过关联.数据库模式看起来与RailsGuide中的示例完全相同.http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association has_many通过关联http://guides.rubyonrails.org/images/has_many_through.png

如何使用ActiveAdmin ...

  1. 在医生页面显示每位患者的预约日期?
  2. 在医生页面中编辑每位患者的预约日期?

谢谢大家.:)

Pet*_*ong 79

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
Run Code Online (Sandbox Code Playgroud)

对于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
Run Code Online (Sandbox Code Playgroud)

  • *快速提示*:确保在患者模型中包含accepts_nested_attributes_for`recepts_nested_attributes_for:约会 (18认同)
  • 对于任何与@Awea有类似问题且无法销毁添加项的人,请确保为嵌套属性启用`:allow_destroy`,请参阅[相关答案](http://stackoverflow.com/questions/4699765/rails-3-纸夹-formtastic-删除图像-附件) (4认同)
  • 我正在做类似的事情,但它最终导致SQL噩梦.每次调用appointment.patient都会生成另一个SQL查询..标准n + 1查询问题.有没有人找到一种方法来做相当于ActiveRecord的急切加载?例如.includes(:病人) (2认同)

Naz*_*zar 14

在回答tomblomfield时,请在评论中跟进问题:

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

  controller do
    def scoped_collection
      YourModel.includes(:add_your_includes_here)
    end
  end
Run Code Online (Sandbox Code Playgroud)

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

HTH