Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails and Model Validation

I want to put some model level validation on 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 (so far) looks like:

class Audio < ActiveRecord::Base
  belongs_to :library
end

Has

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

or

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

?

like image 251
Ash Avatar asked Dec 14 '25 12:12

Ash


1 Answers

To validate the presence of an association, use its name, without _id appended:

validates_presence_of :library

It will validate two things:

  1. library_id is present
  2. a Library with the given id exists

Using validates_presence_of :library_id will only give you the first validation of the two.

In addition to this, the version without _id will also correctly validate if both records are new (and therefore library_id is still unset).

like image 200
molf Avatar answered Dec 16 '25 13:12

molf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!