如何通过关联(具有中介模型的值)为多对多设置固定装置?

How to set up fixtures for many-to-many through association (with values for the intermediary model)?

OrganizationUser 通过 Relationship 建立了 many-to-many 关系。我阅读了 here 关于为 HABTM 协会设置固定装置的内容:

#users.yml
one:
  organizations: one
  email: one@example.com
  ...

#organizations.yml
one:
  name: "Company A"
  ...

这应该在固定装置中的 organizationuser 之间建立关系,并且不需要 relationships.yml 从而使设置保持整洁。

但是,在我的例子中,我需要为关系指定某些变量。例如,在 relationship table 中设置了 moderator 布尔值。我怎样才能在固定装置中包含这些值?我知道我可以通过使用 relationships.yml 并在那里创建我的关系来做到这一点(这就是我目前实现它的方式)。但是不需要 relationships.yml 让它变得更干净。有没有办法为没有 relationships.yml 的关系设置这些变量?例如,类似于:

#users.yml
one:
  organizations: one(moderator: true)
  email: one@example.com
  ...

夹具根本不支持您所指的内联语法。 Fixtures 非常有限,甚至不支持,例如,对通过 has_many 相关的对象进行内联定义。因此,除了向 Rails 提交补丁外,我建议您只有两个选择:

  1. 使用 relationships.yml,就像您已经提到的那样。或者...

  2. 使用 factory_girl 代替固定装置。工厂有自己的一系列问题,但不灵活不是其中之一。

我一直在寻找这个,并想尝试一下我期望它的工作方式。它奏效了。

以下情况:

user has_and_belongs_to_many roles

角色:

# test/fixtures/roles.yml
admin:
  name: admin

donator:
  name: donator

developer:
  name: developer

用户:

# test/fixtures/users.yml
aim:
  reddit_uid: wwkxo
  reddit_name: Elektron1c97
  name: Aim
  sign_in_count: 100
  roles: [admin, developer]

检查 rails 控制台:

irb(main):001:0> User.first.roles.pluck(:name)
  User Load (0.5ms)  SELECT  "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT   [["LIMIT", 1]]
   (0.2ms)  SELECT "roles"."name" FROM "roles" INNER JOIN "roles_users" ON "roles"."id" = "roles_users"."role_id" WHERE "roles_users"."user_id" =   [["user_id", 828945678]]
=> ["admin", "developer"]