2013-04-02 19 views
0

我一直在堅持一段時間如何使用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中的Herb Entry頁面中的用戶能夠創建配方,以便能夠將Herb AUTOMATICALLY作爲配料輸入,並且如果用戶輸入了當前不存在的配料,是否將它作爲新配料輸入(所以其他配方可以使用它)。我不認爲我明白瞭如何使用ActiveAdmin不夠好位指示知道從哪裏開始......這是我到目前爲止有:

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 

我知道這是漫長的,但什麼建議可以給我將不勝感激。我對軌道很陌生。謝謝!

回答

0

如果我正在構建相同的站點,我可能會稍微移動文件的結構以獲得您正在查找的結果。

應用程序/管理/ herb.rb

ActiveAdmin.register Herb do 
end 

這應該是所有你需要在active_admin創建頁面。那麼對於您的應用程序/控制器/ herb_controller.rb

class HerbController < ApplicationController 
def new 
    @herb = Herb.new 
end 
end 

現在我檢查,以確認你可以去ActiveAdmin並創建一個新的藥草。我會進一步添加到您的應用/控制器/ 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 

現在,你想你的香草模型中創建的方法

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 

這是我在堆棧溢出的第一個答案,所以讓我知道這是否對你有幫助!我不久前就與同樣的東西奮鬥,幸運的是有幾個人一路幫助我。

+0

非常感謝!我一定會嘗試這個。它至少在被卡住一段時間之後給我一個去處:...... – fullstrum