简体   繁体   English

工厂女孩协会has_many通过现有对象

[英]factory-girl association has_many through with existing objects

maybe im not phrasing the question right. 也许我说的不是正确的问题。

I have a data structure that looks like this 我有一个像这样的数据结构

A Facility has many users through a Facility role 设施通过设施角色具有许多用户

now in factory gril I know i can create an association like this 现在在工厂里,我知道我可以创建这样的关联

factory :facility_role do
  facility {|f| f.association(:facility)}
  user {|u| u.association(:user)}
  role "ABC"
end

but what I want is to associate it to the first facility if there is one otherwise call the create like it dose in the code above 但是我想要的是将它与第一个设施相关联,如果有的话,请在上面的代码中调用类似的创建

you have access to the currently creating object in your blocks. 您可以访问块中当前创建的对象。 so you can do what you want in your factory. 这样您就可以在工厂中做自己想做的事情。 to make things more clear, you should rename f and u to fr for facility_role. 为了使事情更清楚,您应该将facility_role的f和u重命名为fr。

there are also some callbacks that you can hook into: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#callbacks 您还可以插入一些回调: https : //github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#callbacks

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM