Ruby on rails 如何防止在Rails的关联表中保存无效ID?

Ruby on rails 如何防止在Rails的关联表中保存无效ID?,ruby-on-rails,validation,many-to-many,Ruby On Rails,Validation,Many To Many,我的Rails应用程序中有两个表:类别和服务。我还在它们之间创建了一个关联表CategoriesService,除了验证CategoriesService表上的ID之外,其他一切都正常工作-我刚刚注意到我能够创建一个与不存在的记录的关联。我想知道如何正确地修复它——我怀疑Rails应该让我们创建一些数据库级的验证,这样可以更快更干净。我这样定义了我的模型: class Category < ApplicationRecord has_and_belongs_to_many :servi

我的Rails应用程序中有两个表:
类别
服务
。我还在它们之间创建了一个关联表
CategoriesService
,除了验证
CategoriesService
表上的ID之外,其他一切都正常工作-我刚刚注意到我能够创建一个与不存在的记录的关联。我想知道如何正确地修复它——我怀疑Rails应该让我们创建一些数据库级的验证,这样可以更快更干净。我这样定义了我的模型:

class Category < ApplicationRecord
  has_and_belongs_to_many :services
end

class Service < ApplicationRecord
  has_and_belongs_to_many :categories
end

class CategoriesService < ApplicationRecord
end
类别
我认为创建
has_和_belient_to _many
关系将确保这种验证本身,但我可以看出我错了。我应该如何解决这个问题?

来自:

首选
有很多:通过
有很多并且属于很多。使用
有许多:通过
可以在连接模型上增加属性和验证

就你而言:

class Category < ApplicationRecord
  has_many :categories_services
  has_many :services, through: :categories_services
end

class Service < ApplicationRecord
  has_many :categories_services
  has_many :categories, through: :categories_services
end

class CategoriesService < ApplicationRecord
  belongs_to :category
  belongs_to :service

  # if not using Rails 5:
  validates :category, presence: true
  validates :service, presence: true
  # if using Rails 5, a `belongs_to` will auto-validate the presence
end
从:

首选
有很多:通过
有很多并且属于很多。使用
有许多:通过
可以在连接模型上增加属性和验证

就你而言:

class Category < ApplicationRecord
  has_many :categories_services
  has_many :services, through: :categories_services
end

class Service < ApplicationRecord
  has_many :categories_services
  has_many :categories, through: :categories_services
end

class CategoriesService < ApplicationRecord
  belongs_to :category
  belongs_to :service

  # if not using Rails 5:
  validates :category, presence: true
  validates :service, presence: true
  # if using Rails 5, a `belongs_to` will auto-validate the presence
end