我正在开发我的第一个 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,看看是否有效。
最佳答案
您是否注册了“focus”的复数形式?默认情况下它没有定义,因此您需要定义它(通常在 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
我使用了您引用的模型。
有了这些位,我就可以加载您的种子定义。
关于ruby-on-rails - 如何为具有 HABTM 关系的模型提供与其他种子模型的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3903115/