【问题标题】:Rails 5: How do I point fixtures to other fixtures?Rails 5:如何将灯具指向其他灯具?
【发布时间】:2019-02-22 13:31:01
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    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
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2018-03-22
      • 2018-02-21
      • 1970-01-01
      相关资源
      最近更新 更多