按 % 分配 Ruby Rails 记录更新

Apportion Ruby on Rails record updates by %

我的目标是根据 ID 标记每条记录,但希望按以下方式正确分配:

在"good"和"ok"中,目标是将75%标记为"good",将25%标记为"ok"

我在标记 50-50 时没有问题,因为我可以检查 ID 是否可以被 2 整除

示例:

if (feedback.id.modulo(2) == 0)
  // How can I apportion 75% will be tagged as "good" and 25% as "ok" here?
else
  feedback.update_attributes(status: "very good")
end

在Ruby或Rails中有没有办法根据%条件进行分配?

if (feedback.id.modulo(2) == 0)
  // How can I apportion 75% will be tagged as "good" and 25% as "ok" here?
else
  feedback.update_attributes(status: "very good")
end

很好,但是每次反馈,您都会执行 1 个查询来更新,我认为您可以做得更好

feed_back_ids = FeedBack.ids
FeedBack.where(id: feed_back_ids.pop(feed_back_ids.length/2)).update_all(status: "very good")
FeedBack.where(id: feed_back_ids.pop(feed_back_ids.length*3/4)).update_all(status: "good")
FeedBack.where(id: feed_back_ids).update_all(status: "ok")

如果要随机制作

feed_back_ids = FeedBack.ids.shuffle
FeedBack.where(id: feed_back_ids.pop(feed_back_ids.length/2)).update_all(status: "very good")
FeedBack.where(id: feed_back_ids.pop(feed_back_ids.length*3/4)).update_all(status: "good")
FeedBack.where(id: feed_back_ids).update_all(status: "ok")