在Active Admin中使用select with has_many

时间:2016-11-08 19:32:55

标签: ruby-on-rails activeadmin

Publication可以通过联接类Citation引用其他几个使用has_many关联的出版物。因此,从任何出版物我可以看到它引用的出版物,以及它引用的出版物。

我想使用has_many中的选择器在Active Admin中添加和删除特定出版物的引文。选择器的输入是所有出版物标题及其ID的散列。有数百种出版物可供选择,因此复选框不合适。

显示引用/引用的出版物,并删除引文,工作正常。当我尝试添加新引用的出版物时,我得到:

ActiveRecord::RecordNotFound in Admin::PublicationsController#update
Couldnt find Publication with ID=10 for Publication with ID=2

# Extracted source
def raise_nested_attributes_record_not_found!(association_name, record_id)
  raise RecordNotFound, "Couldn't find #{self.class._reflect_on_association(association_name).klass.name} with ID=#{record_id} for #{self.class.name} with ID=#{id}"
end

# Params (edited)
{
    "publication"=>{
      "cited_publications_attributes"=>{
        "0"=>{"id"=>"7", "_destroy"=>"0"},
        "1"=>{"id"=>"10"}
      }},
    "id"=>"2"
 }

其中10是新增(引用)出版物,2是当前出版物。出版物已经引用了出版物7.我不知道它为什么要搜索出版物10,这是已经存在的记录。

这是我的代码:

模型/ publication.rb

class Publication < ActiveRecord::Base
  has_many :citations
  has_many :cited_publications, :through => :citations
  has_many :inverse_citations, :class_name => "Citation", :foreign_key => "cited_publication_id"
  has_many :citing_publications, :through => :inverse_citations, :source => :publication

  accepts_nested_attributes_for :cited_publications, :allow_destroy => true
end

模型/ citation.rb

class Citation < ActiveRecord::Base
  belongs_to :publication
  belongs_to :cited_publication, :class_name => "Publication"
end

分贝/迁移/ create_citations.rb

class CreateCitations < ActiveRecord::Migration
  def change
    create_table :citations do |t|
      t.references :publication      , index: true, foreign_key: true
      t.references :cited_publication, index: true, foreign_key: true
      t.timestamps null: false
    end
  end
 end

系统管理员/ publication.rb

 ActiveAdmin.register Publication do
  config.sort_order = 'name_asc'
  permit_params :name,
    cited_publications_attributes:    [:id, :name, :_destroy]

  show do
    span b 'Cites: '
    span raw publication.cited_publications.map{ |p| link_to(p.name, admin_publication_path(p)) }.join(", ")
    br
    span b 'Cited by: '
    span raw publication.citing_publications.map{ |p| link_to(p.name, admin_publication_path(p)) }.join(", ")
  end

  form do |f|
    inputs 'Details' do
      publications = Publication.order(:name).map { |p| [p.name, p.id] }
      f.has_many :cited_publications, allow_destroy: true, heading: 'Cited Publications', new_record: 'Add cited publication:' do |c|
        c.input :id, as: :select, collection: publications, label: "Cites", include_blank: false
      end
    end
    br
    actions
  end
end

帮助?我已经坚持了好几个小时。

0 个答案:

没有答案