如何为 MySQL/Rails 中的列获取随机默认值 [英] How do I get a random default value for a column in MySQL/Rails

查看:40
本文介绍了如何为 MySQL/Rails 中的列获取随机默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 mysql 表,其中包含诸如#EE3AA"之类的颜色值.而且我有一个具有颜色属性的模型,该属性是强制性的(应该验证),但不一定需要由用户输入.如果用户留空,我希望使用自动从另一个表中选择的随机值填充它,但默认情况下并不总是相同的值.

Let's say I have a mysql table full of color values like "#EE3AA". And I have a model which has a color attribute, which is obligatory (should validate) but does not need to be entered by the user necessarily. If left empty by the user, I want it to be filled using a random value chosen from another table automatically, but not always the same value by default.

我想,也许,我可以使用迁移来完成,所以它是这样的:

I thought, perhaps, I could do it using a migration, so it is like this:

... :default => "values of the color column of the Colors table".to_a.sample

我的想法在 Ruby 方面可能不正确/不合法.在迁移文件中看到 :default 选项后,我认为每次创建模型时都会运行迁移文件.但阅读米哈伊尔的评论,情况可能并非如此.但无论如何,当用户没有提供任何值时,我如何从另一个表中获取随机值?

My thinking may not be correct/legal in terms of Ruby. After seeing the :default option in the migrations files, I thought that the migration file is run every time a model is created. But reading Mikhail's comment, this may not be the case. But in any case, how I can get a random value from another table when none is supplied by the user?

推荐答案

迁移仅在您创建数据库或更改数据库结构时运行,而不是在保存新记录时运行.Mikhail 建议使用 before_save 回调是正确的.你可以在你的模型中做这样的事情:

Migrations are only run when you create a database or make changes to the structure of the database, not when saving a new record. Mikhail is correct in suggesting a before_save callback. You can do something like this in your model:

class Model < ActiveRecord::Base
  before_save :set_empty_color_to_random_value

  def set_empty_color_to_random_value
    self.color = Color.order("RANDOM()").first.color if self.color.empty?
  end
end

请注意,RANDOM() 适用于 PostgreSQL 和 SQLite,但不适用于 MySQL.对于 MySQL,您必须使用 RAND() 代替.

Note that RANDOM() works for PostgreSQL and SQLite, but not for MySQL. For MySQL you have to use RAND() instead.

这篇关于如何为 MySQL/Rails 中的列获取随机默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆