【问题标题】:Rails, creating associated records along with parent object?Rails,与父对象一起创建关联记录?
【发布时间】:2010-12-31 07:21:20
【问题描述】:

也许我不知道如何询问/搜索这个特定的东西,但基本上我想在创建父对象时创建一些关联模型......假设我有以下情况:

我有一个 Recipe has_many Ingredient 模型...有没有办法一次制作它们,例如这是我的种子任务的一部分:

Recipe.create({
  :title => 'apple pie',
  :description => 'just apple pie',
  :ingredients => {
    [0] => {:title => 'apples'},
    [1] => {:title => 'sugar'},
    [2] => {:title => 'pie crust'}
  }
})

或者我完全疯了?必须有某种类似的方法来执行此操作,无需创建父模型,然后创建所有子模型......等等。

【问题讨论】:

    标签: ruby-on-rails nested-attributes


    【解决方案1】:

    非常接近。见http://apidock.com/rails/v3.0.0/ActiveRecord/NestedAttributes/ClassMethods

    Recipe.create({
      :title => 'apple pie',
      :description => 'just apple pie',
      :ingredients_attributes => [
        { :title => 'apples' },
        { :title => 'sugar' },
        { :title => 'pie crust' }
      ]
    })
    

    请注意,您需要将“accepts_nested_attributes_for :ingredients”放入您的配方模型中。

    【讨论】:

      【解决方案2】:

      您还需要将此添加到您的食谱模型中

      attr_accessible :ingredients_attributes
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-04
        • 2017-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多