Rails 5:如何将灯具指向其他灯具?

Rails 5: How do I point fixtures to other fixtures?

我三个型号 CommentUserProjectProjectComment 需要指向其他对象才能有效。例如,一条评论需要指向一个作者(用户)和一个项目。

相关的夹具文件如下所示:

# comments.yml
test_comment:
  author: users(:test_user)
  project: projects(:test_project)

# users.yml
test_user:
  name: 'test user'

# projects.yml
test_project:
  name: 'Test'
  description: 'This is a test'
  owner: users(:test_user)

但是,我发现我的固定装置可能设置不正确。 Rails returns false 如果我尝试保存评论:

assert_equal true, comments(:test_comment)
#=> false

我可以看到项目和作者有外键:

=> #<Comment:0x00007f9b1661f3d8
 id: 137725605,
 body: "",
 project_id: 745075726,
 author_id: "31ceee04-5307-5059-91db-0dc2068a780c",
 created_at: Fri, 22 Feb 2019 13:17:58 UTC +00:00,
 updated_at: Fri, 22 Feb 2019 13:17:58 UTC +00:00>

但是当我审问他们的时候,Rails returns nil.

> comments(:test_comment).author
=> nil

> comments(:test_comment).project
=> nil

我预计一个会 return users(:test_user) 而另一个会 return projects(:test_project)。我想也许我需要在我的 yaml 中使用 ERB:

test_comment:
  author: <%= users(:test_user) %>
  project: <%= projects(:test_project) %>

但是当我 运行 我的测试时,结果是一连串的错误:

NoMethodError: undefined method `users' for #<#<Class:0x00007f9b17692ff8>:0x00007f9b17692dc8>

我需要做什么才能将灯具指向其他灯具?可以吗?我做错了什么?

Rails guide on Testing with YAML fixtures 中,您可以看到不需要 users(:test_user) 来引用其他对象。相反,您可以简单地写 test_user:

# comments.yml
test_comment:
  author: test_user
  project: test_project

# users.yml
test_user:
  name: 'test user'

# projects.yml
test_project:
  name: 'Test'
  description: 'This is a test'
  owner: test_user

希望对您有所帮助!