简体   繁体   English

我是否需要检查 Rails 中的belongs_to 关联中是否存在记录?

[英]Do I need to check if record exist in a belongs_to association in Rails?

This might be a silly question, but I would like to know if it's a good practice to test if a record exists, even when is a 'belongs_to' association?这可能是一个愚蠢的问题,但我想知道测试记录是否存在是否是一个好习惯,即使是“belongs_to”关联?

For example:例如:

class MyModel < ApplicationRecord
   belongs_to :book

   def my_method
      if self.book.present? # <- Do I need this?
         # Do Something
      end
   end
end

What do you guys think?你们有什么感想? What about when belongs_to :book, optional: true?当belongs_to :book, optional: true 时呢?

It depends, if having the book is mandatory then obviously you don't need to check for the existence of the association.这取决于,如果这本书是强制性的,那么显然您不需要检查关联是否存在。 But if it is not it is a good practice to check or else it might throw an exception when you try to fetch any attribute or make any change on the association.但如果不是,最好检查一下,否则当您尝试获取任何属性或对关联进行任何更改时,它可能会引发异常。 With mandatory I mean this validation:强制性我的意思是这个验证:

validates :book, presence: true

Or having a NOT NULL constraint on the database column or having:或者对数据库列具有NOT NULL约束或具有:

belongs_to :book

without optional: true没有optional: true

Also instead of self.book.present?也代替self.book.present? you could check book_id.present?你可以检查book_id.present? or book.present?book.present? . . Two things here:这里有两件事:

  1. self is redundant, it is not required self是多余的,不是必需的
  2. If you just want to check the association exists or not and don't want to load that from the database you could check book_id.present如果您只想检查关联是否存在并且不想从数据库加载它,您可以检查book_id.present

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

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