如何从父级创建子模型

时间:2015-09-25 07:45:02

标签: ruby-on-rails model controller nested

我已经旋转了,可能会在这里使用Rails轮子几天。我使用了三种模式:IngredientBaseIngredientIngredientListIngredientBase包含一个字符串,可能是" Chicken"," Eggs"或"培根。"成分将有一个Ingredient和一个数量。 IngredientList会有很多成分。

我希望用户能够在提交IngredientList之前使用ingredient_lists / new并能够创建多个成分。如果没有用户提交多个表单,我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

<强>关联

您所关注的是nested models

嵌套模型基本上允许您将属性附加到一个模型的实例;那些属性被发送到关联模型。

这是通过accepts_nested_attributes_for

实现的
#app/models/ingredient_list.rb
class IngrendientList < ActiveRecord::Base
   has_many :ingredients
   accepts_nested_attributes_for :ingredients
end

#app/models/ingredient.rb
class Ingredient < ActiveRecord::Base
   belongs_to :ingredient_list
end

因为你的模型让我感到困惑,所以我为你改写了结构。我认为你对连接模型等感到困惑:

#app/models/ingredient.rb
class Ingredient < ActiveRecord::Base
   #columns id | name | weight | etc | created_at | updated_at
   has_many :recipe_ingredients
   has_many :recipes, through: :recipe_ingredients
end

#app/models/recipe_ingredient.rb
class RecipeIngredient < ActiveRecord::Base
    #columns id | recipe_id | ingredient_id | quantity | created_at | updated_at
    belongs_to :recipe
    belongs_to :ingredient
    accepts_nested_attributes_for :ingredient
end

#app/models/recipe.rb
class Recipe < ActiveRecord::Base
   #columns id | name | etc | etc | created_at | updated_at
   has_many :recipe_ingredients #-> allows extra attributes
   has_many :ingredients, through: :recipe_ingredients 
   accepts_nested_attributes_for :recipe_ingredients
end

这样您就可以创建Recipe,添加新的Ingredient,并且通常可以让您的模型更加健壮。

以下是如何使其与控制器和视图等一起使用:

#app/controllers/recipes_controller.rb
class RecipesController < ApplicationController
   def new
      @recipe = Recipe.new
   end
   def create
      @recipe = Recipe.new recipe_params
      @recipe.save
   end

   private

   def recipe_params
      params.require(:recipe).permit(:recipe, :params, recipe_ingredients_attributes: [:quantity, ingredient_attributes:[:name]])
   end
end

这将创建一个基本表单,但我们需要包含相关字段。有几种方法可以执行此操作,包括RailsCasts中的“手动”方法和Cocoon

重要的是要注意:

  

您调用嵌套表单字段的每个时间,基本上都是   Rails将f.fields_for的另一个实例添加到您的表单。该   值得注意的是,您需要拥有 child_index   fields_for阻止。这是Rails用于识别字段的内容,   并且需要保持独特。

您可以在an answer I wrote some time back上看到有关此内容的更多信息。

对于您的表单,您需要以下内容:

#app/views/recipes/new.html.erb
<%= form_for @recipe do |f| %>
   <%= f.text_field :title %> 
   <%= render "ingredients", locals: {f: f, child_index: Time.now.to_i}  %>
   <%= link_to "Add Ingredient", recipes_add_field_path, class: "ingredient" %>
   <%= f.submit %>
<% end %>

#app/views/recipes/_ingredients.html.erb
<%= f.fields_for :recipe_ingredients, child_index: child_index do |ri| %>
    <%= ri.text_field :quantity %>
    <%= ri.fields_for :ingredient do |ingredient| %>
       <%= ingredient.text_field :name %>
       <%= ingredient.text_field :weight %>
    <% end %>
<% end %>

#config/routes.rb
resources :recipes do
   member "add_field", to: "recipes#add_field"
end

#app/controllers/recipes_controller.rb
class RecipesController < ApplicationController
   def add_field
      @recipe = Recipe.new
      @recipe.recipe_ingredients.build.build_ingredient
      render "new"
   end
end

#app/assets/javascripts/application.js
$(document).on("click", "a.ingredient", function(){
   $.ajax({
      url: '/recipes/add_field',
      success: function(data){
        el_to_add = $(data).html();
        $('#recipes').append(el_to_add);
      }
      error: function(data){
         alert("Sorry, There Was An Error!");
      }
   });
});

答案 1 :(得分:0)

处理嵌套关系的最佳方法是使用accept_nested_attributes

为了更好地进行低估,这里是link

要在表单中管理ui级别表单,请gem