首页 > 解决方案 > Rails 5:如何将灯具指向其他灯具?

问题描述

我三个模型CommentUserProjectProject并且Comment需要指向其他对象才能有效。例如,评论需要指向作者(用户)和项目。

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

# 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)

但是,我发现我的灯具可能设置不正确。false如果我尝试保存评论,Rails 会返回:

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 会返回nil.

> comments(:test_comment).author
=> nil

> comments(:test_comment).project
=> nil

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

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

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

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

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

标签: ruby-on-railsruby-on-rails-5.2

解决方案


使用 YAML 夹具进行测试的 Rails 指南中,您可以看到不需要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

希望这可以帮助!


推荐阅读