Reputation: 95
Consider the following two models
class Book < ActiveRecord::Base
has_many :book_reports
enum genre: [:fiction, :nonfiction]
end
class BookReport < ActiveRecord::Base
belongs_to :book
end
I want to validate book_reports so that it only saves those with a genre of :fiction. I can add a before_save hook to check the book association's genre but am curious if there is a better way.
Upvotes: 1
Views: 669
Reputation: 666
You could use custom methods:
validate :belongs_to_fiction_book, on: [:create, :update]
def belongs_to_fiction_book
errors.add(:book, "is not a fiction book.") unless book.genre == "fiction"
end
Upvotes: 2
Reputation: 59
You could possibly use before_create
callback instead so that you can catch the genre a little sooner in the workflow, but otherwise your idea is fairly sound:
Use a call-back to trigger a check on the genre, and if it doesn't match what you're looking for, reject the record and move on.
You could also use the :validates
call-back to validate that self.genre == 'Fiction'
or whatever else you want to check for, and use before_validation
to catch it even sooner.
I recommend reading through the RubyGuides page on Active Record Callbacks to understand a bit more about the workflow, and then use best judgement to decide when to actually check the Genre value you want.
Upvotes: 1