Lets say I have a food model
in the model, every day, people enter how many lbs of pizza/vegetables开发者_运维问答/fruit they eat.
each food is its own column
my issue is, I'd like it so they can only enter that in once (for that food type) every 24 hours (based on created_at).
This possible?
There's two ways I can think of to make this work:
Each field has its own
updated_at
field - the latter is updated when its namesake is changed, and you do a simple validation to check as follows:before_save :check_periodicity def check_periodicity if self.pizza_updated_at > Date.today - 1.day errors.add(:pizza, "You cannot update your pizza values more often than once a day".) end ... similarly for any other fields (you could also find a way to loop this) end
Store each food type in a separate model called
FoodItem
, which would have columns for the food's type, the day, etc. This way, you can have many types of food in your system and not deal with the inelegant bulk of having lots ofx_updated_at
fields.
I don't think it is possible using the standard rails validations, but it should be easy to build your own.
I would start by building a named scope that finds entries on a given day.
Then, in your validates you can use the exists? method to find see if there are any records that already exist that would conflict. Keep in mind that the exists? method will detect the current record by default, so you will have to account for that.
精彩评论