Rails and model verification

I want to put some model level verification in the following table:

create_table :audios do |t|
  t.integer :library_id, :null => false
  t.string :file, :null => false, :limit => 2048
  t.string :name, :limit => 512
  t.timestamps
end

Does this mean that my model, which (for now) looks like this:

class Audio < ActiveRecord::Base
  belongs_to :library
end

It has

class Audio < ActiveRecord::Base
  validates_presence_of :library
  ...

or

class Audio < ActiveRecord::Base
  validates_presence_of :library_id
  ...

?

+3
source share
1 answer

To check for an association, use its name without _id adding:

validates_presence_of :library

He will confirm two things:

  • library_id is present
  • a Librarywith this idexists

Use validates_presence_of :library_idwill only lead to the first check of two.

In addition to this, the version without _idwill also correctly check if both entries are new (and therefore library_idstill not set).

+5
source

Source: https://habr.com/ru/post/1732100/


All Articles