Ben Muschol
Ben Muschol

Reputation: 607

How to perform form validations separate from the model

I have a web app where users can create Lessons and then log information such as the attendance after the lesson. They need to be able to create the Lesson before it actually happens, but there is information afterwards that is required.

How can I require the user to input attendance after the Lesson but allow Lessons to be created without the attendance? Can I do this in one model, or should I create some sort of LessonInformation model that acts as a middle-man? Is my only other option to validate this part with JavaScript?

Upvotes: 0

Views: 28

Answers (1)

dhouty
dhouty

Reputation: 1989

Without seeing any code, I can't give you a specific solution, but this is a general approach that you could then tailor to fit your app.

First add a column to your Lesson model that holds the current status of a given lesson. This could simply be a boolean called finished.

Then you can add a validation rule that only gets run when finished is true, like this:

validates :attendance, presence: true, if: :finished?

Upvotes: 1

Related Questions