ruby-on-rails – 工厂女孩多个has_many通过

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 工厂女孩多个has_many通过前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要创建一些由多个工厂组成的工厂

这是我的模特

  1. Topic
  2. has_many :plan_topics
  3. has_many :plans,:through => :plan_topics
  4.  
  5. PlanTopic
  6. belongs_to :plan
  7. belongs_to :topic
  8.  
  9. Plan
  10. has_many :subscriptions
  11. has_many :members,:through => :subscriptions
  12. has_many :plan_topics
  13. has_many :topics,:through => :plan_topics
  14.  
  15. Subscription
  16. belongs_to :member
  17. belongs_to :plan
  18.  
  19. Member
  20. has_many :subscriptions
  21. has_many :plans,:through => :subscriptions

这就是我所拥有的

  1. Factory.define :topic do |topic|
  2. topic.name "Operations"
  3. end
  4.  
  5. Factory.define :plan do |plan|
  6. plan.title "A test Finance plan"
  7. plan.price "200"
  8. end
  9.  
  10. Factory.define :plan_topic do |plan_topic|
  11. plan_topic.topic {|topic| topic.association(:topic)}
  12. plan_topic.plan {|plan| plan.association(:plan)}
  13. end

我想做的是 – 工厂(:member_with_subscription)

  1. Factory.define :member_with_subscription do |subscription|
  2. subscription.association(:plan_with_topic)
  3. subscription.association(:member)
  4. end

有办法做到这一点吗?

解决方法

考虑使用after_build回调来设置所有必需的依赖项.例如:
  1. Factory.define :member_with_subscription,:class => 'Member' do |m|
  2. m.after_build do |member|
  3. member.subscriptions << Factory.build(:subscription)
  4. end
  5. end

猜你在找的Ruby相关文章