我现在正在处理 sqlite3 上的 DataMapper。我必须定义创建两个表的模型:“公司”和“应用程序”。
每个应用程序都属于一家公司,每个公司都有许多应用程序。我想在我的模型中表示这种关系,但是我向每个类添加了“has n”和“belongs_to”方法,当在一堆应用程序上调用#create 时,App 类停止工作,它们没有插入到数据库中。
如果我没有关联方法,那么一切正常。
这是我的 DataMapper 代码:
DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/app.db")
class Company
include DataMapper::Resource
property :id, Serial
property :company_name,
property :company_id, Text, :unique => true
has n, :apps
end
class App
include DataMapper::Resource
property :id, Serial
property :app_id, Integer
property :bundle_id, Text
property :game_name, Text
property :company_name, Text
property :created_at, DateTime
property :rank, Integer
belongs_to :company
end
DataMapper.finalize.auto_upgrade!
puts 'Database and tables created'
这是我用来填充表格的代码
companies_in_chart.each do |company|
@add_company = Company.create(
:company_name => company["company_name"],
:company_id => company["company_id"]
)
end
puts "Inserted companies into database"
apps_arr.each do |app|
@new_app = App.create(
:app_id => app["app_id"],
:bundle_id => app["bundle_id"],
:game_name => app["game_name"],
:company_name => app["company_name"],
:created_at => app["DateTime"],
:rank => app["rank"]
)
end
puts "Inserted apps into database"
编辑:新代码
#Set up database and apps table
DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/app.db")
class Company
include DataMapper::Resource
property :id, Serial
property :company_name, Text, :required => true, :lazy => false
property :company_id, Text, :required => true, :lazy => false, :unique => true
has n, :apps
end
class App
include DataMapper::Resource
property :id, Serial
property :app_id, Integer, :required => true
property :bundle_id, Text, :required => true, :lazy => false
property :game_name, Text, :required => true, :lazy => false
property :company_id, Text, :required => true, :lazy => false
property :created_at, DateTime
property :rank, Integer
belongs_to :company
end
DataMapper.finalize.auto_upgrade!
puts 'Database and tables created'
#Insert apps and companies into database
apps_arr.each do |app|
# Creates a new company based on app entry if the company does
# not exist in the companies table
@add_company = Company.create(
:company_name => app["company_name"],
:company_id => app["company_id"]
)
@add_app = App.create(
:app_id => app["app_id"],
:bundle_id => app["bundle_id"],
:game_name => app["game_name"],
:company_id => app["company_id"],
:created_at => app["DateTime"],
:rank => app["rank"]
)
end
puts "Inserted app and companies into database"
@company = Company.first
ap @company # => #<Company @id=1 @company_name="Rovio Entertainment Ltd" @company_id="rovio">
ap @company.apps # => [] --I was hoping it would return all of Rovio's apps in the database