所以我有一个属于User的问题模型。最初,我想用属性public:true设置基本问题,每个用户都可以看到我想在seed.rb中创建的这类问题。
然后,随后使用Answer模型。每个用户回答都属于某个问题。
现在问题是为用户创建这些预先提出的问题以回答我在seed.rb中尝试了以下内容:
u = User.new(email: "test@gmail.com", password: "testpass", password_confirmation: "testpass", gender: "M")
questions = u.questions.build(title: "What is your favourite food?")
u.save
我想使用
为视图中的所有用户调用相同的默认问题questions_controller.rb
def index
@questions = Question.all
end
但这似乎没有用,即当我去rails c并运行u时,它是一个未定义的方法..而且u.questions是一个空数组。我手动在控制台中运行这些线路并且它们工作,所以我不确定这里发生了什么。
我做错了什么?
更新开发日志
^[[1m^[[36mUser Load (16.9ms)^[[0m ^[[1mSELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1^[[0m
^[[1m^[[35mQuestion Load (645.9ms)^[[0m SELECT "questions".* FROM "questions" WHERE "questions"."user_id" = $1 [["user_id", 2]]
^[[1m^[[36mActiveRecord::SchemaMigration Load (48.4ms)^[[0m ^[[1mSELECT "schema_migrations".* FROM "schema_migrations"^[[0m
^[[1m^[[36mActiveRecord::SchemaMigration Load (1.0ms)^[[0m ^[[1mSELECT "schema_migrations".* FROM "schema_migrations"^[[0m
^[[1m^[[35m (0.3ms)^[[0m BEGIN
^[[1m^[[36mUser Exists (34.7ms)^[[0m ^[[1mSELECT 1 AS one FROM "users" WHERE "users"."email" = 'anthony@gmail.com' LIMIT 1^[[0m
^[[1m^[[35m (0.3ms)^[[0m ROLLBACK
DEPRECATION WARNING: You didn't set config.secret_key_base. Read the upgrade documentation to learn more about this new config option. (called from service a\
t /usr/local/rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/webrick/httpserver.rb:138)
答案 0 :(得分:2)
我认为问题在于OP在开发数据库中存在错误的数据。
正在运行rake db:drop db:create db:setup
似乎解决了这个问题。