Rails model validation in different context

Mihai

Let's say you have a Product model that is considered valid when is created without a price. But is not allowed to appear on the website without a price.

Maybe is not the best example but just go with it.

How would you go to implement model validation in different contexts ? Other solutions beside conditional validations since the model doesn't require additional fields.

Matzi

Validation is a tool to prevent invalid fields to be created/saved. For display it is rather a filter to prevent valid entities to be shown. You can use conditional validations but that doesn't effect display, only save.

You can either set up a scope or a filter method for items you may want to display. E.g.

scope :visible, where('price is not NULL')

Or if the condition would be too complex (like checking more then a few fields) you should introduce a new (probably flaglike) field to store if the record is ready for display. It can be changed when the model is saved.

before_save :update_ready_to_display
def update_ready_to_display
  ... # checking code here
end
scope :visible, where(ready_to_display: true)

If the condition is dynamic (like depending on the current date, for time limited items), or really complex (e.g. requires a dependency graph, items are valid if all subitems are valid, etc...) you either go for the first solution which is slow, or try to make a timed task to recalculate visibility for individual items.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related