根据Active Admin中的动态复选框保存嵌套的has_many关联

时间:2017-01-12 05:52:14

标签: ruby-on-rails activeadmin ruby-on-rails-5 form-for

代码:

商业模式

class Business < ApplicationRecord
  has_many :business_categories
  has_many :categories, through: :business_categories
  ......
end

类别模型

class Category < ApplicationRecord
   has_many :services
   has_many :business_categories
   has_many :businesses, through: :business_categories
   .....
 end

BusinessCategory模型

class BusinessCategory < ApplicationRecord
  belongs_to :business
  belongs_to :category
  has_many :business_category_services
  has_many :services, through: :business_category_services
  ....
end

class Service < ApplicationRecord
  belongs_to :category
end

和我要设计的表格请看下面的快照。

please have a look on snapshot

  form do |f|
    f.inputs 'Business' do
    f.input :name
    f.input :category_ids, as: :check_boxes, collection: Category.all.map{|category| [category.name, category.id]}
    f.has_many :business_categories, :class=>'select_category', :heading=>'Services',  :new_record=> true do |business_category|
    business_category.input :service_ids, as: :check_boxes, collection: Service.all.map{|service| [service.name, service.id]}, :input_html => { :class => 'services_checkboxes'}
  end
您可以看到

in the snapshot - 所有类别和服务复选框都来自类别和服务表格Category.allService.all.

并且service_ids应该是动态的我的意思是我应该只看到那些基于步骤2中所选类别的服务而不是所有服务。

我该如何实施?

1 个答案:

答案 0 :(得分:0)

对于新记录(商家),您当前的表单很好,但是对于编辑,您的表单应该是这样的:

form do |f|
  f.inputs 'Business' do
  f.input :name
  Category.all.each |category| do
    check_box_tag :category_ids, category.id, @business.categories.include?(category), :name => 'business[category_ids][]'
    label_tag :category_ids, category.id
  end
  f.has_many :business_categories, :class=>'select_category', :heading=>'Services',  :new_record=> true do |business_category|
    Service.all.each |service| do
      check_box_tag :service_ids, service.id, business_category.services.include?(service), :name => 'business[business_categories][service_ids][]'
      label_tag :service_ids, service.id
    end
  end
end

参考:http://millarian.com/rails/quick-tip-has_many-through-checkboxes/