Rails用错误的外键加载灯具

ail*_*nlv 6 ruby sqlite ruby-on-rails fixtures ruby-on-rails-4

我正在使用rails 4.1.0编写一个简单的应用程序.我创建了两个名为Serie和Event的模型,它们之间有一对多的关系(因为在一个Serie中有许多事件).

class Serie < ActiveRecord::Base
  has_many :events
end

class Event < ActiveRecord::Base
  belongs_to :serie
end
Run Code Online (Sandbox Code Playgroud)

我为这些模型创建了以下fixture文件:

#series.yml
---
Serie1:
  name: Whatever

#events.yml      
---
EventSerie11:
  date: 2013-01-01
  value: '124.4'
  serie: Serie1
EventSerie12:
  date: 2013-02-01
  value: '124.2'
  serie: Serie1
Run Code Online (Sandbox Code Playgroud)

问题是,当我通过使用加载这些灯具时rake db:fixtures:load,我得到了错误的事件对象的外键:

$ rails c
Loading development environment (Rails 4.1.0)
2.1.1 :001 > Serie.first.id
  Serie Load (0.2ms)  SELECT  "series".* FROM "series"   ORDER BY "series"."id" ASC LIMIT 1
 => 10
2.1.1 :002 > Serie.first.events.count
  Serie Load (0.3ms)  SELECT  "series".* FROM "series"   ORDER BY "series"."id" ASC LIMIT 1
   (0.2ms)  SELECT COUNT(*) FROM "events"  WHERE "events"."serie_id" = ?  [["serie_id", 10]]
 => 0  
2.1.1 :003 > Event.first.serie
  Evento Load (0.2ms)  SELECT  "events".* FROM "events"   ORDER BY "events"."id" ASC LIMIT 1
  Serie Load (0.3ms)  SELECT  "series".* FROM "series"  WHERE "series"."id" = ? LIMIT 1  [["id", 627975337]]
 => nil 
2.1.1 :004 > Evento.first.serie_id
  Evento Load (0.4ms)  SELECT  "eventos".* FROM "eventos"   ORDER BY "eventos"."id" ASC LIMIT 1
 => 627975337 
Run Code Online (Sandbox Code Playgroud)

所以你看到所有的灯具都在加载,但事件记录被分配了一个不正确的serie_id外键(因为我使用sqlite进行开发,所以没有约束检查).据我所知,每次重置数据库并加载灯具时,Serie记录都会获得一个新ID,但每个事件记录的serie_id字段始终设置为627975337.

在这里读到你可以指定灯具的加载顺序; 但添加线

ENV["FIXTURES"] ||= "series,events" 
Run Code Online (Sandbox Code Playgroud)

到我的environment.rb文件不起作用,也没有运行

rake db:fixtures:load FIXTURES=series,events
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Sha*_*ell 5

我认为 Rails 与您的类/设备名称series. 它尝试寻找一个名为的模型类,Series因为它很难将您的复数名称单数化。(系列是英语单词,其复数与单数相同)。

我强烈怀疑Serie数据库中的实例与您的固定负载完全无关,而是通过另一种方法创建的实例。

serie_id您的活动赛程中使用的内容是正确的。使用的 id 是通过以下方式计算的:

> ActiveRecord::FixtureSet.identify(:Serie1)
=> 627975337
Run Code Online (Sandbox Code Playgroud)

您可以看到它与您的灯具中使用的值相同。

因此,解决方案是,您可以进入活动记录的内部并覆盖加载固定装置的 rake 任务 - 或者您可以将“serie”/“series”的单数/复数版本定义为您想要的而不是什么Rails 正在猜测。在config/application.rb或 初始化程序中,您可以添加:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'serie', 'series'
end
Run Code Online (Sandbox Code Playgroud)

  • 先生,您是一位绅士,一位学者。在这里,多一些名声。 (2认同)