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

时间:2019-02-22 13:31:01

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

我有三个模型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返回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>

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

1 个答案:

答案 0 :(得分:2)

Rails guide on Testing with YAML fixtures中,您可以看到不需要entries = conn.extend.standard.paged_search ( search_base = '', search_filter=(givenName=myName*), attributes=['lastLogon'], generator=True, ) # entry['attributes'] is { 'lastLogon': [] } # adExplorer shows a valid value 来引用其他对象。相反,您只需编写users(:test_user)

test_user

希望这会有所帮助!