Rails - 允许用户在特定时间范围内仅执行几次某些操作
Rails - allows user to do some actions only few times within certain timeframe
我有 Rails api,我用它从移动应用程序上传照片。有没有办法从 Rails 后端设置类似计时器的东西,让一个用户在一小时内只上传两次 and/or 另一个用户一天两次?我对它如何从后端工作的逻辑感到有点困惑,因为我不想从前端进行。任何建议表示赞赏。谢谢!
简单。只需检查用户在分配的时间范围内创建了多少记录。假设您有以下关联:
class User
has_many :photos
end
class Photo
belongs_to :user
end
还有一个 current_user
方法,returns 经过身份验证的用户。
要根据您使用的时间范围进行查询 range:
def create
@photo = current_user.photos.new(photo_params)
unless current_user.photos.where(created_at: (1.hour.ago..Time.now)).count <= 2
@photo.errors.add(:base, 'You have reached the upload limit')
end
# ...
end
稍后重构时,您可以将其作为 custom validation.
移动到模型中
我有 Rails api,我用它从移动应用程序上传照片。有没有办法从 Rails 后端设置类似计时器的东西,让一个用户在一小时内只上传两次 and/or 另一个用户一天两次?我对它如何从后端工作的逻辑感到有点困惑,因为我不想从前端进行。任何建议表示赞赏。谢谢!
简单。只需检查用户在分配的时间范围内创建了多少记录。假设您有以下关联:
class User
has_many :photos
end
class Photo
belongs_to :user
end
还有一个 current_user
方法,returns 经过身份验证的用户。
要根据您使用的时间范围进行查询 range:
def create
@photo = current_user.photos.new(photo_params)
unless current_user.photos.where(created_at: (1.hour.ago..Time.now)).count <= 2
@photo.errors.add(:base, 'You have reached the upload limit')
end
# ...
end
稍后重构时,您可以将其作为 custom validation.
移动到模型中