[英]How to create an item in a deeply nested form in activeadmin/formtastic
關於如何在ActiveAdmin中使用formtastic創建深度嵌套的表單,我已經停留了一段時間。 這是我的模型結構的示例:
class Herb < ActiveRecord::Base
has_one :medicinal
attr_accessible :medicinal_attributes
accepts_nested_attributes_for :medicinal
草葯有一種葯(使用)
class Medicinal < ActiveRecord::Base
attr_accessible :recipe_attributes
belongs_to :herb
has_and_belongs_to_many :recipes
accepts_nested_attributes_for :recipes
葯物(用途)可以有許多食譜
class Recipe < ActiveRecord::Base
has_and_belongs_to_many :medicinals
has_many :recipe_ingredients
has_many :ingredients, :through => :recipe_ingredients
attr_accessible :recipe_ingredients_attributes
accepts_nested_attributes_for :recipe_ingredients
食譜可以有很多成分(通過recipe_ingredients)
class RecipeIngredient < ActiveRecord::Base
attr_accessible :ingredient_attributes
belongs_to :recipe
belongs_to :ingredient
成分
class Ingredient < ActiveRecord::Base
attr_accessible :item
has_many :recipes, :through => :recipe_ingredients
所以這是我的問題。 我希望用戶能夠從ActiveAdmin的“草葯輸入”頁面中創建配方,並能夠自動將“草葯”作為成分輸入,並且如果用戶輸入了當前不存在的成分,將其作為新成分輸入(以便其他食譜可以使用它)。 我認為我不太了解如何在ActiveAdmin中很好地使用contoller,以至於不知道從哪里開始。這是我到目前為止的內容:
ActiveAdmin.register Herb do
controller do
def new
@herb = Herb.new
@herb.build_medicinal
end
def edit
@herb = Herb.find(params[:id])
if @herb.medicinal.blank?
@herb.build_medicinal
end
end
end
form do |f|
f.inputs "Herb" do
f.inputs :name => "Medicinal", :for => :medicinal do |med|
med.input :content, :label => "Medicinal Uses", :required => true
med.has_many :recipes do |r|
r.inputs "Recipe" do
r.has_many :recipe_ingredients do |i|
i.inputs "Ingredients" do
i.input :ingredient
end
end
end
end
end
end
f.actions
end
我知道這很長,但是您能給我的任何建議將不勝感激。 我是Rails的新手。 謝謝!
如果要構建同一站點,則可以稍微移動文件的結構以獲得所需的結果。
app / admin / herb.rb
ActiveAdmin.register Herb do
end
那應該是在active_admin中創建頁面所需的全部。 然后針對您的app / controller / herb_controller.rb
class HerbController < ApplicationController
def new
@herb = Herb.new
end
end
現在,我將檢查以確認您可以轉到ActiveAdmin並創建一個新葯草。 我將進一步添加到您的app / controller / herb_controller.rb中,以檢查在創建草葯時是否需要添加新成分。
...
def create
@herb = Herb.new
if @herb.save
@herb.create_ingredient_if_not_existing
# perform any other actions, such as flash message or redirect
else
# perform action if save not successful
end
end
現在您要在Herb模型中創建方法
def create_if_not_existing
unless Ingredient.where("name = ?", self.name) then
new_ingredient = ingredient.build
new_ingredient.name = self.name
# add extra attributes here if necessary
new_ingredient.save
end
end
然后,您可以確保不會在任何一個模型中都使用類似以下內容的行創建重復項:
validates :name, :uniqueness => true
這是我對Stack Overflow的第一個答案,所以請告訴我這是否對您有幫助! 不久前,我在同一個東西上苦苦掙扎,很幸運地有幾個人幫助我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.