How do you write a migration to rename an ActiveRecord model and its table in Rails?

Here’s an example: class RenameOldTableToNewTable < ActiveRecord::Migration def self.up rename_table :old_table_name, :new_table_name end def self.down rename_table :new_table_name, :old_table_name end end I had to go and rename the model declaration file manually. Edit: In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this: class RenameOldTableToNewTable < ActiveRecord::Migration def change … Read more

How to skip ActiveRecord callbacks? [duplicate]

For Rails 3, ActiveSupport::Callbacks gives you the necessary control. I was just facing the same challenge in a data integration scenario where normally-desirable-callbacks needed to be brushed aside. You can reset_callbacks en-masse, or use skip_callback to disable judiciously, like this: Vote.skip_callback(:save, :after, :add_points_to_user) ..after which you can operate on Vote instances with :add_points_to_user inhibited

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency. The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It’s like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store … Read more

Add a reference column migration in Rails 4

Rails 4.x When you already have users and uploads tables and wish to add a new relationship between them. All you need to do is: just generate a migration using the following command: rails g migration AddUserToUploads user:references Which will create a migration file as: class AddUserToUploads < ActiveRecord::Migration def change add_reference :uploads, :user, index: … Read more

Heroku Postgres Error: PGError: ERROR: relation “organizations” does not exist (ActiveRecord::StatementInvalid)

I had the same problem. To solve it, resetting the database is more easier. heroku rake db:reset (‘heroku run rake db:reset’ if you’re on cedar) heroku rake db:migrate (‘heroku run rake db:migrate’ if you’re on cedar) Then, migration was done successfully for my case 🙂 While this is a good solution in this context, don’t … Read more

ActiveRecord Find By Year, Day or Month on a Date field

Assuming that your “date attribute” is a date (rather than a full timestamp) then a simple where will give you your “find by date”: Model.where(:date_column => date) You don’t want find_by_date_column as that will give at most one result. For the year, month, and day queries you’d want to use the extract SQL function: Model.where(‘extract(year … Read more