简体   繁体   English

Rails 5.0-如何检查记录是否与另一个表关联?

[英]Rails 5.0 - How to check if record is associated on another table?

Before destroying a record, I'd like to check if there are any uses of it on other tables, even if the record itself has no knowledge of said uses . 在销毁记录之前,我想检查一下它是否在其他表上有任何用途, 即使该记录本身不知道所述用途

For example, lets say I have a table of cost_centers , and I have a table of areas . 例如,可以说我有一个表cost_centers ,我有一个表areas

An area has a default cost_center . area具有默认的cost_center cost_centers have no connection with areas . cost_centersareas cost_centers

Which kind of validation can I use in order to prevent the user from destroying a cost_center , in order to keep an area consistent? 我可以使用哪种validation方式来防止用户破坏cost_center ,从而使area保持一致?

In other words, how can I search through the database to find out wether that record is a foreign key of some other record on any other tables? 换句话说,我如何在数据库中搜索以找出该记录是否是其他任何表上其他记录的外键?

When you designed your database, you've probably set all the references up. 在设计数据库时,您可能已经设置了所有引用。 In your migrations, it would look like this: t.references :cost_center . 在您的迁移中,它看起来像这样: t.references :cost_center

If so, your Cost Center Model could have a has_one relationship to each table holding the reference which, in your example, would be has_one :area . 如果是这样,您的成本中心模型可能与每个包含引用的表具有has_one关系,在您的示例中,该引用将是has_one :area

Then, to check if it is actually used, you could have a before_destroy callback to a method that checks if any has_one definition is not null: 然后,要检查它是否被实际使用,可以对一个方法进行检查,该方法具有一个before_destroy回调,该方法检查是否有has_one定义不为null:

class CostCenter < ActiveRecord::Base
  has_one :area
  before_destroy :check_usage

  def check_usage
    !self.area.nil?
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM