我有三个型号:Comment、User和Project。Project和Comment需要指向其他对象才能有效。例如,注释需要指向作者(用户)和项目。
关联的fixture文件如下所示:
# 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)然而,我发现我的fixture可能设置得不正确。如果我尝试保存注释,Rails将返回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返回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>要将装置指向其他装置,我需要做些什么?这是可以做到的吗?我做错了什么?
发布于 2019-02-22 23:21:26
在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希望这能有所帮助!
https://stackoverflow.com/questions/54828231
复制相似问题