Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails generate migration command to insert data into the table

I have a table and I had to add a migration script to add rows in the table. Please help with the rails generate migration command to insert data into the table.

Thanks, Ramya.

like image 286
ramya Avatar asked Nov 17 '11 07:11

ramya


People also ask

What does rails generate migration do?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.

How do I migrate a database in Ruby on Rails?

Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor. The ID column will be created automatically, so don't do it here as well. The method self. up is used when migrating to a new version, self.


2 Answers

You can write regular ruby code inside a migration. So you can simply do something like this:

class Foo < ActiveRecord::Migration
  def self.up
    User.create(:username => "Hello", :role => "Admin")
  end
  def self.down
    User.delete_all(:username => "Hello")
  end
end

Just write regular ruby inside your migration same as you would in pry or rails console.

like image 155
Tigraine Avatar answered Oct 06 '22 23:10

Tigraine


The code helped me is the sql statement as show

In migration file

def up
execute("insert into salary_ranges(salary_range) values('Above 2000');")
end
like image 21
John Avatar answered Oct 07 '22 01:10

John