我的数据库中有一个类别列表(为简洁起见未列出验证)。
class Category < ActiveRecord::Base
has_many :crimes_categories
has_many :crimes, through: :crime_categories
end
我正在为我的数据库播种犯罪,其中一些有多个类别(为简洁起见未列出验证)。
class Crime < ActiveRecord::Base
belongs_to :team
has_many :crime_categories
has_many :categories, through: :crime_categories
end
这些模型由CrimeCategory模型加入
class CrimeCategory < ActiveRecord::Base
belongs_to :category
belongs_to :crime
end
种子文件正在遍历犯罪对象列表以进行格式化并将其添加到我的数据库中。我尝试过几种不同的方法。第一种方法是创建CrimeCategory行。
count = 1
teamCrimeList.each do |crime|
...
categories.each do |cat|
...
end
category_object = Category.where(name: category)
crime_category_objects << category_object
CrimeCategory.create(category_id: category_object.id, crime_id: count)
最后一行会引发以下错误
NameError: uninitialized constant CrimeCategory
我尝试的另一个策略是以下
teamCrimeList.each do |crime|
...
categories.each do |cat|
...
end
category_object = Category.where(name: category)
crime_category_objects << category_object
end
date = Date.parse(crime['Date'])
crime_object = Crime.create(team_id: team.id, date: date, name: crime['Name'], position: crime['Position'], encounter: crime['Encounter'], description: crime['Description'], outcome: crime['Outcome'])
crime_object.categories = crime_category_objects
返回相同的错误
我也试过这种方法
teamCrimeList.each do |crime|
...
categories.each do |cat|
...
end
category_object = Category.where(name: category)
crime_category_objects << category_object
end
date = Date.parse(crime['Date'])
Crime.create(team_id: team.id, categories: crime_category_objects.flatten, date: date, name: crime['Name'], position: crime['Position'], encounter: crime['Encounter'], description: crime['Description'], outcome: crime['Outcome'])
我扔了一些撬,试着打电话给crime.categories
,所有这些都会返回相同的错误。
我搜索了堆栈溢出,我在这个问题上遇到的几乎所有条目都与命名错误有关,但就我所知,没有命名错误。
答案 0 :(得分:0)
@Glyoko有正确的想法。我将我的CrimeCategory模型文件命名为
app/models/crimecategory.rb
代替app/models/crime_category.rb