我在seeds.rb
中有这段代码:
user = User.create({email: "test@mail.com", login:"test_account", password: "password123"})
article=user.articles.build({:name=>"Test Article",
:description=>"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.",
:body=> "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ,
:approved => true})
article.save!
但是当我去控制台时:
2.1.1 :001 > Article.last
Article Load (0.8ms) SELECT "articles".* FROM "articles" ORDER BY "articles"."id" DESC LIMIT 1
=> #<Article id: 15, name: "Test Article", description: "Lorem ipsum dolor sit amet, consectetur adipisicin...", body: "Lorem ipsum dolor sit amet, consectetur adipisicin...", approved: true, user_id: nil, created_at: "2016-01-30 22:55:58", updated_at: "2016-01-30 22:55:58">
它user_id
等于nil
,这不是我所期望的。
user_id
代替build
方法。
但是当我添加:user_id => user.id
时,它仍然是零,如果我再次使用:user_id => User.last.id
nil,但是当我添加:user_id => 1
或任何手动值时,它会起作用。如果我的最后一个用户id为nil,但它有id 2.