加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何将具有HABTM关系的模型与其他种子模型相关

发布时间:2020-12-17 03:12:12 所属栏目:百科 来源:网络整理
导读:我正在研究我的第一个Rails(3)应用程序,并期待播种一堆数据. 我遇到的问题是我想要种一些与我刚播种的其他模型有一个has_and_belongs_to_many关系的模型.我做的似乎是正确的,但我没有得到我期待的结果. 我有一个Asana模型(简化): class Asana ActiveRecord:
我正在研究我的第一个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",created_at: "2010-10-11 01:48:02",updated_at: "2010-10-11 01:48:02">]

那么,一个人怎么做呢?

或者,有更好的方法吗?

谢谢!

POST ANSWER:

我已经添加了变形:

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,看看是否有效.

解决方法

您是否注册了“焦点”的复数?它没有默认定义,因此您需要定义它(通常在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

我引用了你使用过的模型.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读