Ruby on rails 验证HABTM模型关系的存在性
我有以下型号Ruby on rails 验证HABTM模型关系的存在性,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我有以下型号 class Business < ActiveRecord::Base has_and_belongs_to_many :categories validates_presence_of :category_ids end class Category < ActiveRecord::Base has_and_belongs_to_many :businesses end 编辑: 添加了以下自定义验证方法,但我仍然收到相同的错误,就好像验
class Business < ActiveRecord::Base
has_and_belongs_to_many :categories
validates_presence_of :category_ids
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :businesses
end
编辑: 添加了以下自定义验证方法,但我仍然收到相同的错误,就好像验证没有运行一样
class Business < ActiveRecord::Base
has_and_belongs_to_many :categories
validate :categories_exist
def categories_exist
category_ids.each do |c|
errors.add(:category_ids, :category_doesnt_exist) unless Category.exists? c
end
end
end
class业务
您可以查看gem。这个gem对于验证外键是否对应于合法的父记录非常有用。如自述文件所述:
这个插件库添加了ActiveRecord模型来检查
:所属\保存时关联实际存在
可能有多种方法可以实现这一点,但我建议查看和。谢谢,但我需要验证HATBM关联的存在
class Business < ActiveRecord::Base
has_and_belongs_to_many :categories
validate :categories_exist
def categories_exist
category_ids.each do |c|
errors.add(:category_ids, :category_doesnt_exist) unless Category.exists? c
end
end
end