Activeadmin,复制has_many记录

时间:2015-12-27 14:58:34

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 activeadmin

当我使用ActiveAdmin编辑一个代理商时,我可以选择一个城市并将其与代理商相关联。这个城市与原子能机构有联系,但这个城市一直都在数据库中重复。

我的模特:

# agency.rb
class Agency < ActiveRecord::Base
  has_many :agency_cities
  has_many :cities, through: :agency_cities
  accepts_nested_attributes_for :cities, allow_destroy: true
end

# city.rb
class City < ActiveRecord::Base
  has_many :agency_cities
  has_many :agencies, through: :agency_cities
end

# AgencyCity.rb
class AgencyCity < ActiveRecord::Base
  belongs_to :agency
  belongs_to :city
end

我阅读Activeadmin的文档并添加了[:id] permit_parameter,但我仍然遇到问题,我很困惑。

# admin/agency.rb
ActiveAdmin.register Agency do
  permit_params :name, :picture,
    cities_attributes: [:id, :name, :description, :_destroy]

  form do |f|
     f.inputs "Agencies" do
       f.input :picture, as: :file
       f.input :creation_date, label: 'Creation Date'
       f.input :name, label: 'Name'
     end
   end

   f.inputs do
     f.has_many :cities do |k|
       k.input :name, label: 'City',
         as: :select,
         collection: City.all.map{ |u| "#{u.name}"}
       k.input :_destroy, as: :boolean
     end
   end
   f.actions
end

2 个答案:

答案 0 :(得分:1)

您可以在生成的html中检查城市选择输入中的选项值是城市的名称(而不是ID)。 试试这种方式:}

一些参考:http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

答案 1 :(得分:1)

您正尝试将现有城市与代理商相关联,因此,您应该这样做:

ActiveAdmin.register Agency do
  permit_params city_ids: [] # You need to whitelist the city_ids

  form do |f|
    f.inputs "Agencies" do
      f.input :picture, as: :file
      f.input :creation_date, label: 'Creation Date'
      f.input :name, label: 'Name'
      f.input :cities, as: :check_boxes, checked: City.pluck(&:id) # this will allow you to check the city names that you want to associate with the agency
    end
  end
end

这样,您就可以将选定的城市与相应的代理商相关联,而无需在数据库中创建(复制)新城市。我认为这就是你要找的东西: - )