Ruby FactoryGirl ActiveRecord::RecordInvalid:验证失败:已使用名称
我有三种模式,课程、类别和合作伙伴,一门课程可以有多个类别,一门课程属于一个合作伙伴。创建课程工厂时,出现以下错误:Ruby FactoryGirl ActiveRecord::RecordInvalid:验证失败:已使用名称,ruby,ruby-on-rails-4,factory-bot,factory,Ruby,Ruby On Rails 4,Factory Bot,Factory,我有三种模式,课程、类别和合作伙伴,一门课程可以有多个类别,一门课程属于一个合作伙伴。创建课程工厂时,出现以下错误: Partner has a valid factory for course Failure/Error: expect(FactoryGirl.create(:course)).to be_valid ActiveRecord::RecordInvalid: Validation failed: Name has already been ta
Partner has a valid factory for course
Failure/Error: expect(FactoryGirl.create(:course)).to be_valid
ActiveRecord::RecordInvalid:
Validation failed: Name has already been taken
以下是我的模型:
class Category < ActiveRecord::Base
has_many :categorisations
has_many :courses, :through=> :categorisations
belongs_to :user
#validation
validates :name, presence: true , uniqueness: { scope: :name }
end
class Partner < ActiveRecord::Base
has_many :courses
belongs_to :user
validates :name, presence: true, uniqueness: { scope: :name }
validates :short_name, presence: true
VALID_HEX_COLOR= /\A#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})\z/
validates :primary_color, presence: true, format: { with: VALID_HEX_COLOR}
validates :secondary_color, presence: true, format: { with: VALID_HEX_COLOR}
end
class Course < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: [:slugged, :history]
has_many :categorisations, :dependent => :destroy
has_many :categories, :through=> :categorisations
belongs_to :partner
belongs_to :user
# validates_uniqueness_of :title
validates :title, presence: true
# validates :start_date, presence: true
# validates :duration, presence:true
# validates :state, presence:true
validates :categories, length: { minimum: 1 , message:"please select"}
validates :partner_id, presence: true, allow_nil: false
end
我不确定我做错了什么,如果有人能告诉我问题可能是什么,或者我可以着手解决这个问题的过程可能是什么,那将是一个很大的帮助尝试一下:
factory :partner do |f|
f.sequence(:name) { |n| "#{Faker::Name.name} #{n}" }
f.short_name "UCT"
f.primary_color "#009bda"
f.secondary_color "#002060"
end
factory :category do |f|
f.sequence(:name) { |n| "Category #{n}" }
end
我所要做的就是在我的课程工厂中添加以下行:
categories {[FactoryGirl.create(:category)]}
factory :course do |f|
f.title "Introduction to Accounting short course"
f.start_date "2014-02-27 00:00:00"
f.duration "10 WEEKS ONLINE"
partner
categories {[FactoryGirl.create(:category)]}
end
库斯工厂:
categories {[FactoryGirl.create(:category)]}
factory :course do |f|
f.title "Introduction to Accounting short course"
f.start_date "2014-02-27 00:00:00"
f.duration "10 WEEKS ONLINE"
partner
categories {[FactoryGirl.create(:category)]}
end
它尝试了这个,但我得到了一个erorr:失败/错误:无法从回溯系统中找到匹配的行StackError:堆栈级别太深我想你需要删除分类工厂。好的,很酷,但不确定该调用什么来创建关联?@Andrew_tainton尝试使用回调创建关联在这种情况下感谢您的帮助,它最终让我找到了正确的答案