Skip validation for related objects - rails activerecord

class Author
  has_many :books

  validates :email, :presence => true
end

class Book
  belongs_to :author

  validates :title, :presence => true
end

Skipping checks is easy:

a = Author.new
a.save(:validate => false)

However, I need to skip authorization of the author when creating the book, without skipping checking the books, for example:

b = Book.new
b.title = "A Book"

b.author = Author.last
b.save
+5
source share
2 answers

I do not quite understand your question. In your example, you are not creating any new author object:

>     b = Book.new
>     b.title = "A Book"
>     
>     b.author = Author.last
>     b.save

If you are trying to create a new author without email, you cannot just do:

b = Book.new
b.title = "A Book"

author = Author.new
author.save(:validate => false)

b.author = author
b.save

Hmm ... maybe I just missed something obvious here.

0
source

Since author authorization doesn’t seem so important when saving your model, you can write your book model as follows:

class Book
  belongs_to :author, :validate => false

  validates :title, :presence => true
end

, .

0

All Articles