rake db:种子由于某种原因不想构建关联

时间:2016-01-30 22:59:19

标签: ruby-on-rails

我在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.

0 个答案:

没有答案