How to generate SQL Server database from schema.rb file? - mysql

I have an MS SQL Server 2012 instance with managment studio and I have schema.rb file which contains the following:
# This file is auto-generated from the current state of the database.
# Note that this schema.rb definition is the authoritative source for your database schema.
ActiveRecord::Schema.define(:version => 20120525100324) do
create_table "academic_details", :force => true do |t|
t.integer "registration_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "additional_exam_groups", ["school_id"], :name => "index_additional_exam_groups_on_school_id", :limit => {"school_id"=>nil}
create_table "additional_exam_scores", :force => true do |t|
t.integer "student_id"
t.integer "additional_exam_id"
t.decimal "marks", :precision => 7, :scale => 2
t.integer "grading_level_id"
t.string "remarks"
t.boolean "is_failed"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "school_id"
end.................etc.
How to generate SQL Server database from that file?

First, is your Rails app properly configured to use MS SQL Server 2012 as its DB?
If so, try running rake db:schema:load task.
If that doesn't work, try running the rake db:setup task.
You can find more detailed information about the rake tasks here in this previous Stackoverflow answer: https://stackoverflow.com/a/10302357/631834

Related

Mysql database migration failing on Rails

I have this migration file:
class InitialDigitizationWork < ActiveRecord::Migration
def self.up
create_table :digitizations do |t|
t.string :submission_code, :null => false
t.timestamps
end
add_index :digitizations, :submission_code, :unique => true
create_table :digitized_pieces do |t|
t.integer :digitization_id, :null => false
t.integer :position, :null => false
t.string :piece_type, :default => "Page"
t.timestamps
end
add_index :digitized_pieces, :digitization_id
create_table :digitized_views do |t|
t.integer :digitized_piece_id, :null => false
t.string :initial_file_name
t.string :attachment_file_name
t.string :attachment_content_type
t.integer :attachment_file_size
t.datetime :attachment_updated_at
t.integer :position, :null => false
t.boolean :is_primary, :default => false
t.timestamps
end
add_index :digitized_views, :digitized_piece_id, :null => false
end
and it fails on the last line:
-- add_index(:digitized_views, :digitized_piece_id, {:null=>false})
rake aborted!
StandardError: An error has occurred, all later migrations canceled:
Unknown key: :null. Valid keys are: :unique, :order, :name, :where, :length, :internal, :using, :algorithm,
Anyone have any idea what is going on?
What's annoying here is that since the last line fails, I can't rerun the migration again because the table on top digitizations exists. I know how to use Postgresql and access the specific table that is created specified by this yml file:
#SQLite version 3.x
#gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
adapter: mysql2
database: arthouse_development
username: root
password:
host: localhost
port: 3306
#socket: /tmp/mysql.sock
legacy_development:
adapter: mysql2
database: arthouse_legacy_development
username: root
password:
host: localhost
port: 3306
Anyone know how I can console into the database here?
Anyone know what might be going on? This is my first time using mysql and could use some help.
also when I type in mysql this happens:
mysql
ERROR 1045 (28000): Access denied for user 'jwan'#'localhost' (using password: NO)
but this works:
mysql -u root
Do I have to do that everytime?
Ok so here is what you need to do:
First rollback your last migration so that you begin on a clean slate:
rake db:rollback
Then remove the default=> null constraint on your indexes. The error message states explicitly that it's not a known key:
Unknown key: :null. Valid keys are: :unique, :order, :name, :where,
:length, :internal, :using, :algorithm,
Then rerun the migration:
rake db:migrate

MySQL Syntax error: unexpected keyword_do_block

I am very new to Ruby and trying to complete a tutorial that I can't get to work properly. I am attempting to run rake db:migrate on my root folder and is giving me 3 separate error messages:
>rake db:migrate
rake aborted!
SyntaxError:
C:/Users/Bill/Sites/simple_cms/db/migrate/20170922050429_create_use
rs.rb:4: syntax error, unexpected keyword_do_block
create_table :users, do |t|
^
C:/Users/Bill/Sites/simple_cms/db/migrate/20170922050429_create_users.rb:5:
syntax error, unexpected tSTRING_BEG, expecting keyword_end
t.column "first_name", :string, :limit => 25
^
C:/Users/Bill/Sites/simple_cms/db/migrate/20170922050429_create_users.rb:5:
syntax error, unexpected ',', expecting keyword_end
t.column "first_name", :string, :limit => 25
^
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
The Ruby code from my create_users.rb file is:
class CreateUsers < ActiveRecord::Migration[5.1]
def change
create_table :users, do |t|
t.column "first_name", :string, :limit => 25
t.string "last_name", :limit => 50
t.string "email", :default => "", :null => false
t.string "password", :limit => 40
t.timestamps
end
end
I am not sure what I am doing wrong here. Any insight would be appreciated!
in addition to first answer. Why don't you use rails generators?
Write migrations can be usefull when you have to modify something. Faster and cleaner way is using rails generators:
Example:
rails g model User first_name:string last_name:string
If attributes are string you can just
rails g model User first_name last_name
It will generate class User in /app/models/user.rb and migration for database.
Also you have Scaffold, and others generators.
More info: Command Line Rails
Tip: Check for Devise Gem, it will generate entire structure for User Model.
Link: Devise Gem
In your code:
def change
create_table :users, do |t|
t.column "first_name", :string, :limit => 25
t.string "last_name", :limit => 50
t.string "email", :default => "", :null => false
t.string "password", :limit => 40
t.timestamps
end
end
You have:
create_table :users, do |t|
which should be:
create_table :users do |t|
There should not be any comma after that unless you have more than one arguments there.
Update:
And also you class has no end which will not close the class definition and throw exception.
On a side note:
You have this line:
t.column "first_name", :string, :limit => 25
which can be written as:
t.string "first_name", :limit => 25
Hope this helps.

rake db:migrate not creating table

I'm just following this RoR tut, I'm doing it the same way but I'm stuck creating a table:
$ rails generate model User
invoke active_record
create db/migrate/20140718180319_create_users.rb
create app/models/user.rb
invoke test_unit
create test/models/user_test.rb
create test/fixtures/users.yml
This is my xxxxx_create_users.rb
class CreateUsers < ActiveRecord::Migration
def Up
create_table :users do |t|
t.column "first_name", :string, :limit => 25
t.string "last_name", :limit => 50
t.string "email", :default => "", :null => false
t.string "password", :limit => 40
t.timestamps
end
end
def down
drop_table :users
end
end
When I run db:migrate the table is not being created:
$ rake db:migrate
== 20140718182504 CreateUsers: migrating ======================================
== 20140718182504 CreateUsers: migrated (0.0000s) =============================
Is missing
create_table(:users)
-> x.xxxxxs
What am I doing wrong? Thanks.
Isn't it a typo with your "Up" migration method? Try with:
def up
instead of:
def Up

Rails :Inserting values into Mysql table

I have a table admin_users. Model named AdminUser.
Schema is
ActiveRecord::Schema.define(version: 20130915031734) do
create_table "admin_users", force: true do |t|
t.string "first_name", limit: 25
t.string "last_name", limit: 50
t.string "email", limit: 100, default: "", null: false
t.string "username", limit: 25
t.datetime "created_at"
t.datetime "updated_at"
t.string "password_digest"
end
add_index "admin_users", ["username"], name: "index_admin_users_on_username", using: :btree
How can I insert values into the table ??
I tried this ( Image below)
Using rails console
It is best to use a db/seeds.rb file and run rake db:seed (or similar mechanism) to populate a database.
Within a migration you have access to the full application environment. That means you can use your model classes, but since models can change over time it is not very safe to reference them within migrations. In migrations you may also execute arbitrary SQL using the execute method.
With the file db/seeds.rb, the Rails have given us a way of feeding default values easily and quickly to a fresh installation. This is a normal Ruby program within the Rails environment. You have full access to all classes and methods of your application.
So you do not need to enter everything manually with rails console in order to make the records created in the section called “create” available in a new Rails application, but you can simply use the following file db/seeds.rb:
Sample Code.
Country.create(name: 'Germany', population: 81831000)
Country.create(name: 'France', population: 65447374)
Country.create(name: 'Belgium', population: 10839905)
Country.create(name: 'Netherlands', population: 16680000)
Other than Seeds, you can use migration file for the same.
ActiveRecord::Schema.define(version: 20130915031734) do
create_table "admin_users", force: true do |t|
t.string "first_name", limit: 25
t.string "last_name", limit: 50
t.string "email", limit: 100, default: "", null: false
t.string "username", limit: 25
t.datetime "created_at"
t.datetime "updated_at"
t.string "password_digest"
end
add_index "admin_users", ["username"], name: "index_admin_users_on_username", using: :btree
/*Add your script here to insert some predifined value.*/
AdminUsers.create(first_name: 'Nair', email: 'nair#gmail.com', username: 'nairg' )
AdminUsers.create(first_name: 'Nair1', email: 'nair1#gmail.com', username: 'nairg1' )
AdminUsers.create(first_name: 'Nair2', email: 'nair2#gmail.com', username: 'nairg2' )
/* ... So on as per your requirement */
end
To Generate Seed file : Generating Seeds Blog
you can make create method in controller to save data,
def create
#admin_user = Admin_user.new(admin_users_params)
if #admin_user.save
redirect_to :action => "index"
else
render action: 'new'
end
end
def admin_users_params
params.require(:admin_user).permit(:first_name, :last_name, :email, :username)
end

Is Ruby on Rails appropriate for what I am trying to achieve? Creating CRUD scaffolds for existing MySQL database

I have previously created localhost-only RoR applications where models were created manually with scaffolds generated for them, creating a nice, quick, easy to use CRUD interface for the data. I did this in Netbeans using SQLite.
Now I have a server with a MySQL database and wish to create a quick CRUD application which provides a quick and easy way to view data in the database and give a few options like edit/delete. As my database is already specified by MySQL this seems to open up a massive can of worms, making this a lot less straight forward in comparison to my Netbeans venture into scaffold-generated crud web apps in RoR.
I have looked into dumping the schema of my current database, db:raking it, then generating the scaffolds. Is this the correct approach? I have also read about Magic Model Generator. Is this the best way to go about getting the MySQL database to a RoR model format? http://magicmodels.rubyforge.org/magic_model_generator/
I guess what I'm asking is, for my database structure, is RoR appropriate to mock-up a quick CRUD web app so that the data can have basic manipulation performed on it?
Below is the schema.rb for my MySQL database. There is a FK relationship on userId and attachmentId.
ActiveRecord::Schema.define(:version => 0) do
create_table "attachments", :primary_key => "attachmentId", :force => true do |t|
t.string "attachmentName", :null => false
t.string "fileType", :limit => 30, :null => false
t.binary "content", :null => false
t.string "printCode"
end
create_table "emails", :primary_key => "emailId", :force => true do |t|
t.integer "userId", :limit => 11, :null => false
t.integer "attachmentId", :limit => 11, :null => false
t.string "body", :limit => 1000
t.string "subject"
end
add_index "emails", ["attachmentId"], :name => "attachmentId", :unique => true
add_index "emails", ["userId"], :name => "userId"
create_table "printUsers", :primary_key => "userId", :force => true do |t|
t.string "email", :null => false
end
add_index "printUsers", ["email"], :name => "email", :unique => true
end
There seem to be several approaches to using rails with an existing database. See Connect rails to existing postgres DB - models not seen by console and controllers, and especially the links from it: http://magicmodels.rubyforge.org/magic_model_generator/ and http://blog.aizatto.com/2007/05/21/activerecord-without-rails/
It's good to point out that you don't need to use ActiveRecord with rails. Your model can be any Object, so it might be easier to use something like sequel or arel to access the data.
Another approach would be to migrate the data out of your existing database and into a new one that you generate by scaffolding your models.