【问题标题】:How do you seed models with HABTM relationships to other seeded models您如何将具有 HABTM 关系的模型播种到其他播种模型
【发布时间】:2010-10-12 01:31:09
【问题描述】:

我正在开发我的第一个 Rails(3) 应用程序,并希望收集大量数据。

我遇到的问题是我想播种一些与我刚刚播种的其他模型具有 has_and_belongs_to_many 关系的模型。我正在做看起来正确的事情,但我没有得到我期望的结果。

我有一个体式模型(简化):

class Asana < ActiveRecord::Base
  has_and_belongs_to_many :therapeutic_foci
end

和 TherapeuticFocus 模型:

class TherapeuticFocus < ActiveRecord::Base
  has_and_belongs_to_many :asanas
end

在我的 db/seeds.rb 中,我创建了一些 TherapeuticFoci:

tf = TherapeuticFocus.create([
  {:name => 'Anxiety'},
  {:name => 'Asthma'},
  {:name => 'Fatigue'},
  {:name => 'Flat Feet'},
  {:name => 'Headache'},
  {:name => 'High Blood Pressure'},
  {:name => 'Stress'} ])

然后创建一个体式:

asanaCreate = Asana.create!([
  { :english_name => 'Mountain Pose', 
    :traditional_name => 'Tadasana', 
    :pronunciation => 'TadaSANA', 
    :deck_set => 'Basic', 
    :type => 'Standing', 
    :therapeutic_foci => TherapeuticFocus.where("name in ('Stress','Flat Feet')")}
])

结果是创建了 TherapeuticFocus 模型,创建了 Asana,但它没有创建与 TherapeuticFocus 模型的关系。结果数组为空。

如果我跑步

TherapeuticFocus.where("name in ('Stress','Flat Feet')")

在 Rails 控制台中,我得到了预期的两条记录:

irb(main):010:0> TherapeuticFocus.where("name in ('Stress','Flat Feet')")
=> [#<TherapeuticFocus id: 6, name: "Flat Feet", description: nil, created_at: "2010-10-11     01:48:02", updated_at: "2010-10-11 01:48:02">, 
    #<TherapeuticFocus id: 19, name: "Stress",     description: nil, created_at: "2010-10-11 01:48:02", updated_at: "2010-10-11 01:48:02">]

那么,如何做到这一点?

或者,有没有更好的方法来做到这一点?

谢谢!

发布答案:

我已经添加了变形:

ActiveSupport::Inflector.inflections do |inflect|
    inflect.irregular 'focus', 'foci'
end

我的联接表迁移如下所示:

create_table :asanas_therapeutic_foci, :id => false do |t|
  t.references :asana, :therapeutic_focus
end

我将尝试将其更改为 t.belongs_to 而不是 t.references,看看是否可行。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    您是否注册了“焦点”的复数形式?默认没有定义,所以需要自己定义(一般在config/initializers/inflections.rb):

    ActiveSupport::Inflector.inflections do |inflect|
      inflect.irregular 'focus', 'foci'
    end
    

    您还需要确保您的迁移已为 HABTM 关联定义了正确的连接表。这是我使用的“向上”迁移的相关部分:

        create_table :asanas do |t|
          t.string :english_name
          t.string :traditional_name
          t.string :pronunciation
          t.string :deck_set
          t.string :type
        end
        create_table :therapeutic_foci do |t|
          t.string :name
        end
        create_table :asanas_therapeutic_foci, :id => false do |t|
          t.belongs_to :asana
          t.belongs_to :therapeutic_focus
        end
    

    我使用了你引用的模型。

    有了这些位,我就可以加载你的种子定义了。

    【讨论】:

    • 啊哈,我想通了 - 我意识到我可以在 rake db:setup 期间查看 development.log,并且发现我的问题源于属性“:therapeutic_foci”不是可批量分配的。解决这个问题,一切正常。谢谢!
    猜你喜欢
    • 2019-10-20
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2021-05-13
    • 1970-01-01
    相关资源
    最近更新 更多