Choosing random in rails sqlite vs mysql
Hi guys I am trying to fetch random data from a database in Ruby on Rails. Unfortunately sqlite and mysql use different names for the "random" function. Mysql uses rand (), sqlite uses random (). So far, I am very happy with the use of sqlite in my development environment and I don't want to give it up.
So, I have a solution for this, but I'm not very happy with it. First, is there a cleaner abstraction in RoR for getting a random function? If not, what is the best way to get an "adapter"?
# FIXME: There has to be a better way...
adapter = Rails.configuration.database_configuration[Rails.configuration.environment]["adapter"]
if adapter == "sqlite3"
# sqllite calls it rand
random = "random"
else
# mysql calls it rand
random = "rand"
end
query.push("SELECT *, (" + random + "() * (0.1 * value)) AS weighted_random_value...")
I ran into this issue while developing locally using SQLite. Unfortunately, this is not the only difference between the databases you intend to run (for example, booleans are handled differently).
Is SQLite and MySQL support required? If not, I recommend switching to one database: the one you are deploying to production.
It takes a little longer to set up, but IMHO it will ultimately save you time and have confidence that your application works well in the database you will actually deploy it to.
source to share