使用select或create选项在active_admin中嵌套的表单

时间:2011-08-25 22:43:37

标签: ruby-on-rails ruby-on-rails-3 belongs-to activeadmin

我们正在使用active_admin作为管理后端。

我们有一个模型“App”:belongs_to model“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 个答案:

答案 0 :(得分: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关系),但我设法让它为我工作。如果此代码输出任何错误,请告诉我。

答案 1 :(得分:7)

form_builder类支持名为has_many的方法。

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

那应该做的。

更新:我重新阅读了您的问题,这只允许添加新的发布商,我不知道如何进行选择或创建。

答案 2 :(得分:5)

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

您只需要执行以下操作:

f.input :publisher

答案 3 :(得分: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]
相关问题