What's the best way of going about this. Is there something I can put in the migrations? Thanks in advance.
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.
where returns an ActiveRecord::Relation (not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation. find (and its related dynamic find_by_columnname methods) returns a single model object.
This is database specific. Just do something like the following in your migration:
class MyMigration < ActiveRecord::Migration
def self.up
create_table :my_table do |t|
# ...
end
execute "ALTER TABLE my_table AUTO_INCREMENT = 1000" # for MySQL
end
def self.down
# ...
end
end
Or indeed, even better, as suggested by Bane:
def self.up
create_table :my_table, :options => "AUTO_INCREMENT = 1000" do |t|
# ...
end
end
Be cautious with database-specific migrations, though! Using any SQL that is specific to your database will break compatibility with other databases and is generally not a good idea.
Any string passed into the ":options" option will be appended to the end of the SQL statement that creates the table. Best practice.
def self.up
create_table :my_table, :options => "AUTO_INCREMENT = 1000" do |t|
# ...
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With