工厂女孩——理解关联
我还没有找到关于 association
方法的作用以及如何正确使用它的明确解释 - 我看到几个例子,其中模型 Alpha has_many Beta ,然后当使用我们说的工厂创建新的 Beta 时beta.association :alpha
或类似的东西。但Alpha不是也与Beta相关吗(Beta属于Alpha)……所以我很困惑。我认为关联(至少在普通英语中)通常是相互的,所以我不明白这个方法应该做什么。有人可以澄清一下吗?
除了在广泛的概念层面上理解它之外,我还想确切地知道它在语法层面上的作用(即它是否添加像 attr_accessor 那样的方法?就像它实际上在做什么?)
抱歉,我只是没有对此找到了一个明确的解释——如果有人能向我解释这一点那就太好了!
I haven't found a clear explanation for what the association
method does and how to use it properly -- I see several examples where model Alpha has_many Beta and then when creating a new Beta using a Factory we say beta.association :alpha
or something along those lines. But isn't Alpha also associated with Beta (Beta belongs_to Alpha)... so I'm just pretty confused. I thought an association (at least in normal English) is usually mutual, so I am not understanding what this method is supposed to do. Can someone please clarify this?
In addition to understanding it on a broad conceptual level, I would also like to know exactly what it does on a syntactical level (ie. is it adding methods like attr_accessor does? like what is this actually doing??)
Sorry I just have not found a clear explanation for this -- if anyone can explain this to me that would be great!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据我的经验,当您需要在工厂创建其他对象时实例化关联对象时,您可以在 FactoryGirl 中定义“关联”,如果没有此关联,您的新对象将无效。
假设您有 Company 和 Worker 模型,并且在您的应用程序中您进行了验证,以防止创建具有无效 company_id 属性的 Worker。您可以拥有没有工人的公司(这就是为什么您不应该为工厂中的工人定义关联),但您不能拥有没有公司的工人。然后,您可以将工厂中的关联添加到为创建的每个 Worker 惰性实例化 Company 中。
总而言之,当模型中有“belongs_to”,并且模型中的关联也具有存在验证时,您就可以定义关联。
From my experience you define "association" in FactoryGirl when you need to instantiate associated object while creating other object by factory, and without this association your new object would be invalid.
Let's say you have Company and Worker models, and in your application you have validations which prevent creating Worker with invalid company_id attribute. You can have Company without workers (that's why you shouldn't define association for workers in factory), but you can't have Worker without Company. You then add association in factory to lazy-instantiate Company for every Worker created.
So to summarize - you define association when you have
belongs_to
in model, and when your association in model also have presence validation.