ruby-on-rails - Rails 5:如何将灯具指向其他灯具?
问题描述
我三个模型Comment
,User
和Project
。Project
并且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>
我需要做什么才能将灯具指向其他灯具?可以做到吗?我做错了什么?
解决方案
在使用 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
希望这可以帮助!
推荐阅读
- c - SDL 正在播放 wav 文件,但我似乎无法播放简单的波形
- javascript - 表单和网格 Extjs 之间的绑定
- makefile - 无法使用 catkin_make 构建 ROS 包。对包树感到困惑
- spring - 如何使用 MockHttpSession 和 Junit 进行模拟
- json - 如何在 Swift 中使用带有自定义类型值的可解码协议?
- javascript - 如何从 Ionic 4 中的 TypeScript 文件调用 iframe 显示的网页中的 JavaScript 函数?
- kotlin - 具有多种类型的 Equals 重载使运算符 '==' 不能应用于
- php - 在while循环中计算总和到数组
- php - Laravel 主机不允许连接到这个 mysql 服务器(Centos 7)
- swift - 将html转换为字符串时如何设置NSAttributedString的字体大小?