Ruby on rails Activeadmin,复制有很多记录

Ruby on rails Activeadmin,复制有很多记录,ruby-on-rails,ruby,ruby-on-rails-3,ruby-on-rails-4,activeadmin,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: t

当我使用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

您可以在生成的html中检查city select输入中的选项值是否为城市名称(而不是id)。 试着这样做:
collection:City.all.map{| u |[u.name,u.id]}

一些参考资料:


您正试图将现有城市与机构联系起来,因此,您应该这样做:

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

这将允许您将所选城市关联到相应的机构,而无需在数据库中创建(复制)新城市。我想这就是你想要的:-)

集合:City.all.map{| u |[u.name,u.id]}
选项值是id,而不是城市名称。当我用一个城市更新代理时,条目仍然是重复的,但是新条目有这个html
1
(我假设1是重复条目的id)问题可能在您提到的代码行中,我会处理它,谢谢
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