Ruby on rails 如何在两个表之间使用验证?新浪博客采集简单实例
我有一个表Ruby on rails 如何在两个表之间使用验证?新浪博客采集简单实例,ruby-on-rails,ruby,ruby-on-rails-6,Ruby On Rails,Ruby,Ruby On Rails 6,我有一个表项目和一个表promsitems有一列prom和prom有一列promname,我想在我的item模型中验证'prom.是否存在(:promanme=>:prom),然后创建,否则我还没有存储该prom class Item < ApplicationRecord validates :prom_exist? def prom_exist? if Prom.exists?(:promane => :prom) else end end 类项
项目
和一个表proms
items
有一列prom
和prom
有一列promname
,我想在我的item
模型中验证'prom.是否存在(:promanme=>:prom),然后创建,否则我还没有存储该prom
class Item < ApplicationRecord
validates :prom_exist?
def prom_exist?
if Prom.exists?(:promane => :prom)
else
end
end
类项:Prom)
其他的
结束
结束
您应该能够执行以下操作:
class Item < ApplicationRecord
validate :prom_exists
def prom_exists
errors.add(:prom, 'does not exist') if prom && !Prom.exists?(promnane: prom)
end
end
class Item < ApplicationRecord
belongs_to :prom
end