开发者

Rails - 1 entry in model per field, per day

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:

  1. 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
    
  2. 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 of x_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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜