我正在开发我的第一个Rails(3)应用程序,并希望播种一堆数据。
我遇到的问题是,我想要播种一些模型,这些模型与我刚刚播种的其他模型具有has_and_belongs_to_many关系。我正在做看起来正确的事情,但是我没有得到我所期望的结果。
我有一个Asana模型(简化):
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'} ])然后创建一个Asana:
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,看看是否有效。
发布于 2010-10-11 13:28:11
你注册了复数形式的“焦点”了吗?默认情况下不定义它,因此您需要定义它(通常在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我使用了你所引用的模型。
有了这些内容,我就能够加载您的种子定义了。
https://stackoverflow.com/questions/3903115
复制相似问题