Skip validation for related objects - rails activerecord

拟墨画扇 提交于 2019-12-21 17:11:59

问题


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 validations when creating a book without skipping books validations, like this:

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

b.author = Author.last
b.save

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4313748/skip-validation-for-related-objects-rails-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!