19

我们将 active_admin 用于我们的管理后端。

我们有一个模型“App”:belongs_to 模型“Publisher”:

class App < ActiveRecord::Base
  belongs_to :publisher
end

class Publisher < ActiveRecord::Base
  has_many :apps
end

在为“App”模型创建新条目时,我希望可以选择现有发布者或(如果尚未创建发布者)以相同(嵌套)形式(或至少没有离开页面)。

有没有办法在 active_admin 中做到这一点?

这是我们目前所拥有的(在 admin/app.rb 中):

form :html => { :enctype => "multipart/form-data" } do |f|
  f.inputs do
    f.input :title
    ...
  end

  f.inputs do
    f.semantic_fields_for :publisher do |p| # this is for has_many assocs, right?
      p.input :name
    end
  end

  f.buttons
end

经过数小时的搜索,我将不胜感激任何提示......谢谢!

4

4 回答 4

9

首先,确保在您的 Publisher 模型中,您对关联对象具有正确的权限:

class App < ActiveRecord::Base
  attr_accessible :publisher_attributes

  belongs_to :publisher
  accepts_nested_attributes_for :publisher, reject_if: :all_blank
end

然后在您的 ActiveAdmin 文件中:

form do |f|
  f.inputs do
    f.input :title
    # ...
  end

  f.inputs do
    # Output the collection to select from the existing publishers
    f.input :publisher # It's that simple :)

    # Then the form to create a new one
    f.object.publisher.build # Needed to create the new instance
    f.semantic_fields_for :publisher do |p|
      p.input :name
    end
  end

  f.buttons
end

我在我的应用程序中使用了稍微不同的设置(而不是 has_and_belongs_to_many 关系),但我设法让它为我工作。让我知道此代码是否输出任何错误。

于 2012-11-01T22:11:07.143 回答
7

form_builder类支持一个名为has_many.

f.inputs do
  f.has_many :publisher do |p|
    p.input :name
  end
end

那应该做的工作。

更新:我重新阅读了您的问题,这只允许添加新的发布者,但我不确定如何选择或创建。

于 2011-09-06T04:55:39.227 回答
5

根据 ActiveAdmin:http ://activeadmin.info/docs/5-forms.html

您只需要执行以下操作:

f.input :publisher
于 2012-08-16T09:59:51.000 回答
0

我发现你需要做 3 件事。

为表单添加语义字段

f.semantic_fields_for :publisher do |j|
  j.input :name
end

向控制器添加一个nested_belongs_to 语句

controller do
    nested_belongs_to :publisher, optional: true
end

使用关键字属性更新控制器上允许的参数以接受参数

permit_params publisher_attributes:[:id, :name]
于 2017-01-06T17:52:30.377 回答