开发者

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 validations is easy:

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

However, I need skip author vali开发者_JAVA技巧dations when creating a book without skipping books validations, like this:

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

b.author = Author.last
b.save


I quite did not 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 an email, can't you just do:

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

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

b.author = author
b.save

Hmm... maybe I'm just missing something obvious here.


Since author validation seems not so important while saving your model, you could write your Book model like this:

class Book
  belongs_to :author, :validate => false

  validates :title, :presence => true
end

This way, authors validations will be skipped while saving.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜