簡體   English   中英

使用select或create選項在active_admin中嵌套的表單

[英]Nested form in active_admin with select or create option

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

經過幾個小時的搜索,我會感激任何暗示......謝謝!

首先,確保在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關系),但我設法讓它為我工作。 如果此代碼輸出任何錯誤,請告訴我。

form_builder類支持名為has_many的方法。

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

那應該做的。

更新:我重新閱讀了您的問題,這只允許添加新的發布者,我不知道如何進行選擇或創建。

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

你只需要做如下:

f.input :publisher

我發現你需要做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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM