繁体   English   中英

如何在activeadmin / formtastic中以深度嵌套的形式创建项目

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM