gpt4 book ai didi

ruby - FactoryGirl ActiveRecord::RecordInvalid:验证失败:名称已被占用

转载 作者:太空宇宙 更新时间:2023-11-03 16:26:45 27 4
gpt4 key购买 nike

我有三个模型,Course、Category 和 partner,一个类(class)可以有多个类别,一个类(class)属于一个合作伙伴。当我创建我的类(class)工厂时,出现以下错误:

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.name Faker::Name.name
f.short_name "UCT"
f.primary_color "#009bda"
f.secondary_color "#002060"
end

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
categorisation
end
factory :categorisation do |categorisation|
categorisation.category {|category| category.association(:category)}
categorisation.course {|course| course.association(:course)}
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

关于ruby - FactoryGirl ActiveRecord::RecordInvalid:验证失败:名称已被占用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23648526/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com