ruby-on-rails – factory_girl中的has_and_belongs_to_many关联
发布时间:2020-12-17 02:14:28 所属栏目:百科 来源:网络整理
导读:我是factory_girl的新手,并试图找出如何有效地为以下模型生成工厂: class Company ActiveRecord::Base has_and_belongs_to_many :tagsendclass Tags ActiveRecord::Base has_and_belongs_to_many :companies validates :type,:inclusion = { :in = %w(marke
我是factory_girl的新手,并试图找出如何有效地为以下模型生成工厂:
class Company < ActiveRecord::Base has_and_belongs_to_many :tags end class Tags < ActiveRecord::Base has_and_belongs_to_many :companies validates :type,:inclusion => { :in => %w(market location) } end 我已经看过StackOverflow上的先前答案(包括this one),但是大多数都已经过时和/或没有正确的答案.有没有人可以用Factorygirl帮助定义这两个对象的工厂? 更新 这就是我到目前为止所提出的问题 FactoryGirl.define do factory :tag do id 448 trait :market do type "market" end trait :location do type "location" end name "software" end factory :company do id 1234 name "Apple Inc." factory :company_with_tags do #setting the default # of tags for companies ignore do tag_count 2 end after(:create) do |company,evaluator| FactoryGirl.create_list(:tag,evaluator.tag_count,company: company) end end end end 解决方法
我认为问题是关联名称指定不正确.标签有很多公司,而不是一个,所以:
after(:create) do |company,evaluator| FactoryGirl.create_list(:tag,companies: [company]) end 作为旁注,您希望避免使用type作为列名,除非您尝试设置多态关系. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |