如何在两个表之间使用验证? Ruby 在 rails
How can I use validates between two tables ? Ruby on rails
我有一个 table items
和一个 table proms
。 items
有一个列 prom
并且 prom
有一个列 promname
,我想在我的 item
模型中验证 `Prom.exists?(: promanme => :prom) 然后创建其他我还没有存储那个舞会
class Item < ApplicationRecord
validates :prom_exist?
def prom_exist?
if Prom.exists?(:promane => :prom)
else
end
end
您应该能够执行以下操作:
class Item < ApplicationRecord
validate :prom_exists
def prom_exists
errors.add(:prom, 'does not exist') if prom && !Prom.exists?(promnane: prom)
end
end
虽然我会建议制作一个外键约束并使用舞会的 id
而不是它的名称,而 Item
只会有 prom_id
而 item.prom
会获取Prom
记录。然后它会简单地喜欢:
class Item < ApplicationRecord
belongs_to :prom
end
我有一个 table items
和一个 table proms
。 items
有一个列 prom
并且 prom
有一个列 promname
,我想在我的 item
模型中验证 `Prom.exists?(: promanme => :prom) 然后创建其他我还没有存储那个舞会
class Item < ApplicationRecord
validates :prom_exist?
def prom_exist?
if Prom.exists?(:promane => :prom)
else
end
end
您应该能够执行以下操作:
class Item < ApplicationRecord
validate :prom_exists
def prom_exists
errors.add(:prom, 'does not exist') if prom && !Prom.exists?(promnane: prom)
end
end
虽然我会建议制作一个外键约束并使用舞会的 id
而不是它的名称,而 Item
只会有 prom_id
而 item.prom
会获取Prom
记录。然后它会简单地喜欢:
class Item < ApplicationRecord
belongs_to :prom
end