【发布时间】:2017-10-18 02:15:03
【问题描述】:
我在我的应用程序中添加了用于登录的设计 gem。我的页面是一家商店,一个用户有很多订单,我添加了模型用户:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :comandas #I add this line, comandas = orders in Spanish
end
在 Comandas(orders) 的迁移文件中我添加了这个:
class CreateComandas < ActiveRecord::Migration[5.0]
def change
create_table :comandas do |t|
t.belongs_to :user, index: true #references to user
t.float :total
t.timestamps
end
end
end
现在我正在使用种子文件测试数据库,但是当我向用户添加 Comanda 时,这会引发我 rake 被中止的错误。
我的种子文件:
c1 = Comanda.create(total: 100)
u1 = User.find_by email: "aaa@aaa.cat"
u1.comandas << [c1]
我之前创建了用户。
更新:
我终于找到了问题所在。问题是我在添加此修改之前创建了所有模型。当我添加这个关系时,Rails 并没有改变我的数据库。我检查了这个进入 sqlite 命令行并列出 Comandas 表的列。我看到对用户的引用不在这里。并决定删除所有执行此命令的数据库:
rake db:drop db:create db:migrate
添加用户并运行后:
rake db:seed
并且有效! 感谢大家的帮助!
【问题讨论】:
-
您不想先创建用户吗?
-
我已经创建了用户,因为当我执行 rake db:seed 时没有将 Comanda 添加到用户的最后一行,它可以工作。
-
删除最后一行并不能证明
u1不为空 -
我只是检查一下,我这样做:User.find_by_email("aaa@aaa.cat").email 并返回:aaa@aaa.cat
-
在运行 rake db:seed 之前是否运行过 rake db:migrate?如果没有尝试
标签: ruby-on-rails ruby database ruby-on-rails-4 rake