Rails Generate Scaffold With Foreign Key

This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.

1 Command Line Basics

Rails Scaffold Foreign Key

There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:

Scaffold

How to Create a Blog from Scratch Using Ruby on Rails. ruby script/generate scaffold post title:string body:text. You might have noticed the text “post:references”. This will be used to create the foreign key field for linking to the primary key of the posts table.

  • rails console
  • rails server
  • rails test
  • rails generate
  • rails db:migrate
  • rails db:create
  • rails routes
  • rails dbconsole
  • rails new app_name
  • Upgrading Ruby on Rails. This guide provides steps to be followed when you upgrade your applications to a newer version of Ruby on Rails. These steps are also available in individual release guides.
  • Ruby on Rails is an open source framework you can use to build Web sites and Web-based databases. Of course, as with any programming language, you need to know Ruby’s keywords and Rail’s naming conventions. Making sure that your data meets validation standards is key, and the proper iterators make traveling amongst your data a.

You can get a list of rails commands available to you, which will often depend on your current directory, by typing rails --help. Each command has a description, and should help you find the thing you need.

Let's create a simple Rails application to step through each of these commands in context.

1.1 rails new

The first thing we'll want to do is create a new Rails application by running the rails new command after installing Rails.

You can install the rails gem by typing gem install rails, if you don't have it already.

Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.

1.2 rails server

The rails server command launches a web server named Puma which comes bundled with Rails. You'll use this any time you want to access your application through a web browser.

With no further work, rails server will run our new shiny Rails app: https://renewbang960.weebly.com/blog/fbs-mt5-download-for-mac.

With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open http://localhost:3000, you will see a basic Rails app running.

You can also use the alias 's' to start the server: rails s.

The server can be run on a different port using the -p option. The default development environment can be changed using -e.

The -b option binds Rails to the specified IP, by default it is localhost. You can run a server as a daemon by passing a -d option.

1.3 rails generate

The rails generate command uses templates to create a whole lot of things. Running rails generate by itself gives a list of available generators:

You can also use the alias 'g' to invoke the generator command: rails g.

You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!

Using generators will save you a large amount of time by writing boilerplate code, code that is necessary for the app to work.

Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:

All Rails console utilities have help text. As with most *nix utilities, you can try adding --help or -h to the end, for example rails server --help.

The controller generator is expecting parameters in the form of generate controller ControllerName action1 action2. Let's make a Greetings controller with an action of hello, which will say something nice to us.

What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a JavaScript file, and a stylesheet file.

Check out the controller and modify it a little (in app/controllers/greetings_controller.rb):

Generate

Then the view, to display our message (in app/views/greetings/hello.html.erb):

Fire up your server using rails server.

The URL will be http://localhost:3000/greetings/hello.

With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the index action of that controller.

Rails comes with a generator for data models too.

For a list of available field types for the type parameter, refer to the API documentation for the add_column method for the SchemaStatements module. The index parameter generates a corresponding index for the column.

But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A scaffold in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.

We will set up a simple resource called 'HighScore' that will keep track of our highest score on video games we play.

The generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the high_scores table and fields), takes care of the route for the resource, and new tests for everything.

The migration requires that we migrate, that is, run some Ruby code (living in that 20130717151933_create_high_scores.rb) to modify the schema of our database. Which database? The SQLite3 database that Rails will create for you when we run the rails db:migrate command. We'll talk more about that command below.

Let's talk about unit tests. Unit tests are code that tests and makes assertionsabout code. In unit testing, we take a little part of code, say a method of a model,and test its inputs and outputs. Unit tests are your friend. The sooner you makepeace with the fact that your quality of life will drastically increase when you unittest your code, the better. Seriously. Please visitthe testing guide for an in-depthlook at unit testing.

Let's see the interface Rails created for us.

Go to your browser and open http://localhost:3000/high_scores, now we can create new high scores (55,160 on Space Invaders!)

1.4 rails console

The console command lets you interact with your Rails application from the command line. On the underside, rails console uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.

You can also use the alias 'c' to invoke the console: rails c.

You can specify the environment in which the console command should operate.

If you wish to test out some code without changing any data, you can do that by invoking rails console --sandbox.

1.4.1 The app and helper objects

Inside the rails console you have access to the app and helper instances.

With the app method you can access named route helpers, as well as do requests.

With the helper method it is possible to access Rails and your application's helpers.

1.5 rails dbconsole

rails dbconsole figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL (including MariaDB), PostgreSQL, and SQLite3.

You can also use the alias 'db' to invoke the dbconsole: rails db.

1.6 rails runner

runner runs Ruby code in the context of Rails non-interactively. For instance:

You can also use the alias 'r' to invoke the runner: rails r.

You can specify the environment in which the runner command should operate using the -e switch.

You can even execute ruby code written in a file with runner.

1.7 rails destroy

Think of destroy as the opposite of generate. It'll figure out what generate did, and undo it.

You can also use the alias 'd' to invoke the destroy command: rails d.

1.8 rails about

rails about gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.

1.9 rails assets:

You can precompile the assets in app/assets using rails assets:precompile, and remove older compiled assets using rails assets:clean. The assets:clean command allows for rolling deploys that may still be linking to an old asset while the new assets are being built.

If you want to clear public/assets completely, you can use rails assets:clobber.

1.10 rails db:

The most common commands of the db: rails namespace are migrate and create, and it will pay off to try out all of the migration rails commands (up, down, redo, reset). rails db:version is useful when troubleshooting, telling you the current version of the database.

More information about migrations can be found in the Migrations guide.

1.11 rails notes

rails notes searches through your code for comments beginning with a specific keyword. You can refer to rails notes --help for information about usage.

By default, it will search in app, config, db, lib, and test directories for FIXME, OPTIMIZE, and TODO annotations in files with extension .builder, .rb, .rake, .yml, .yaml, .ruby, .css, .js, and .erb.

1.11.1 Annotations

You can pass specific annotations by using the --annotations argument. By default, it will search for FIXME, OPTIMIZE, and TODO.Note that annotations are case sensitive.

1.11.2 Tags

You can add more default tags to search for by using config.annotations.register_tags. It receives a list of tags.

1.11.3 Directories

You can add more default directories to search from by using config.annotations.register_directories. It receives a list of directory names.

1.11.4 Extensions

You can add more default file extensions to search from by using config.annotations.register_extensions. It receives a list of extensions with its corresponding regex to match it up.

1.12 rails routes

rails routes will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.

1.13 rails test

A good description of unit testing in Rails is given in A Guide to Testing Rails Applications

Rails comes with a test framework called minitest. Rails owes its stability to the use of tests. The commands available in the test: namespace helps in running the different tests you will hopefully write.

1.14 rails tmp:

The Rails.root/tmp directory is, like the *nix /tmp directory, the holding place for temporary files like process id files and cached actions.

The tmp: namespaced commands will help you clear and create the Rails.root/tmp directory:

  • rails tmp:cache:clear clears tmp/cache.
  • rails tmp:sockets:clear clears tmp/sockets.
  • rails tmp:screenshots:clear clears tmp/screenshots.
  • rails tmp:clear clears all cache, sockets, and screenshot files.
  • rails tmp:create creates tmp directories for cache, sockets, and pids.

1.15 Miscellaneous

  • rails stats is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
  • rails secret will give you a pseudo-random key to use for your session secret.
  • rails time:zones:all lists all the timezones Rails knows about.

Rails Generate Scaffold With Foreign Keys

1.16 Custom Rake Tasks

Custom rake tasks have a .rake extension and are placed inRails.root/lib/tasks. You can create these custom rake tasks with therails generate task command.

To pass arguments to your custom rake task:

You can group tasks by placing them in namespaces:

Invocation of the tasks will look like:

If you need to interact with your application models, perform database queries, and so on, your task should depend on the environment task, which will load your application code.

2 The Rails Advanced Command Line

More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.

2.1 Rails with Databases and SCM

When creating a new Rails application, you have the option to specify what kind of database and what kind of source code management system your application is going to use. This will save you a few minutes, and certainly many keystrokes.

Let's see what a --git option and a --database=postgresql option will do for us:

We had to create the gitapp directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration:

It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database.

The only catch with using the SCM options is that you have to make your application's directory first, then initialize your SCM, then you can run the rails new command to generate the basis of your app.

Feedback

You're encouraged to help improve the quality of this guide.

Please contribute if you see any typos or factual errors. /anno-1404-venice-multiplayer-key-generator.html. To get started, you can read our documentation contributions section.

You may also find incomplete content or stuff that is not up to date. Please do add any missing documentation for master. Make sure to check Edge Guides first to verify if the issues are already fixed or not on the master branch. Check the Ruby on Rails Guides Guidelines for style and conventions.

If for whatever reason you spot something to fix but cannot patch it yourself, please open an issue.

And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the rubyonrails-docs mailing list.


Ruby, Rails and MySQL gem ― through scaffolding, versioning, rake db:create, db:migrate ― HOW to implement and preserve your schema with SQL
Posted by: mike montagne
Date: March 23, 2010 06:16PM

WHY
As RoR initiates will immediately wonder how they're going to deploy table designs meeting usual SQL standards across scaffolding processes which lack even a power to express vital design concerns as we would with the usual CREATE TABLE statement, the following instructions provide the necessary pattern for implementing your intended SQL schema through development, testing, and deployment, while preserving the RAD advantages of scaffolding processes which otherwise seemingly preclude purposed schemas. This simple approach virtually eliminates any reliance on utilities; and it preserves intended SQL table designs across development, testing and deployment with a single line of code.
In other words, it resolves the necessary pattern for working to conventional SQL standards in RoR.
BACKGROUND
RoR (Ruby on Rails) 'scaffolding' generates project skeleton code from a database design. Because it so efficiently generates any necessary framework for our eventual application, scaffolding is a fundamental tool of the RoR approach to RAD.
Scaffolding commands are issued from the command line. For instance, if we're working with MySQL, we would create the outer RoR MySQL skeleton for our application by a simple command: 'rails myApp -d mysql'. This command produces the basic framework for our dynamic web application, together with definitions for three versions of our database ― each named for development, testing ('test'), and production respectively, concatenated from the myApp parameter of the rails command.
Subsequent 'scaffold' commands generate somewhat crude definitions for each table of our databases, together with further skeleton code to manage and interface the table. This further skeleton code will support generic RoR processes, which we then customize into a finished application. The important thing to understand insofar as these instructions are concerned, is that these scaffold commands just generate a crude definition of each table. They do not create the table. We're going to take advantage of this to intervene on the process at this point to create and preserve our tables with conventional SQL CREATE TABLE statements.
For example, a scaffold command to generate a definition for an amendments table might be:
script/generate scaffold amendment c_code:string c_name:string tran_id:integer priority:integer
Issuing this command from the command prompt generates the further skeleton code to support generic operations on this particular table of our development, test, and production databases. Again, it does not create the table. It creates a crude definition of the table which will subvert many design purposes. Tables are created later by a 'rake db:migrate' command. The purpose of these instructions is to overcome the design limitations imposed by the crude 'database agnostic' table definitions of scaffold processes.
Although it does generate skeleton code which operates on the fields we have crudely defined by scaffolding, this table-defining juncture of the skeleton generating phase provides us a necessary opportunity to plant a line of code in each table's Create[Tablename] self.up method. This one line of code creates the table instead by our usual SQL CREATE TABLE statement, ensuring every conceivable purpose of good schema designs, as opposed to tolerating the database agnostic dilutions of scaffold table definitions. Thus our basic process likewise preserves the advantages of scaffolding for RAD generation of our skeleton modules. Once we have defined tables with scaffold commands, we simply modify each table's create method. Then we continue development in the usual manner.
Thus, as in all the usual subsequent processes, we first create *our database* (just a home for our tables) with the usual 'rake db:create' instruction. We can then create our tables from whatever kind of definition exists in each table's create method. The tables are created (or altered) by issuing 'rake db:migrate'. If we hadn't modified each of our table create methods, the usual 'rake db:migrate' function would create our tables from the crude scaffold definition which initially resides in create self.up. Instead, because we have planted a comprehensive SQL CREATE TABLE statement in every table create method, our migrate functions will always, always, always create our tables from a far more powerful, articulate, and optimization-capable SQL approach.
Thus after our modification of the create method, all our tables are always created and altered by the conventional 'rake db:migrate' instruction. The undesirable scaffold definition of our table is gone for good; it can never affect our work; and except for the brief pause to modify the create method as instructed, our work proceeds in all the usual manners.
To integrate our tables with RoR philosophies however, we must further understand that 'script/generate' scaffold commands automatically define three additional fields for each of our tables: an integer field named 'id' and made the primary key; together with two fields which the resultant .rb file refers to as 'timestamps'. The latter are actually DATETIME field types, named 'created_at' and 'updated_at' respectively. The SQL statement we plant in the create methods of each table's .rb file must perform this responsibility itself, because these fields are required by skeletonized application functions.
Scaffold commands create a dated .rb file for each table definition. These files, named (for versioning purposes) [DateTimeExpr]_create_[TableName].rb for each table, will be generated in a [project]/db/migrate/ directory. It is in each of these files that we find the table create method for each of our tables, to perform the negligible task of replacing the auto-generated code with our necessary SQL CREATE TABLE statement.
To summarize. after we plant our SQL CREATE TABLE statement in each of these files, the three versions of our database are created according to the usual pattern. We create a home for our database by issuing 'rake db:create'. Then our tables can be created and altered as necessary by issuing 'rake db:migrate'.
PROBLEMS
RoR scaffolding doesn't support a multitude of native MySQL field types which are vital to good table designs, efficient resource usage, and efficient throughput. In the database agnostic scheme of scaffolding, highly purposed field types ― TINYINT, SMALLINT, MEDIUMINT, BIGINT, DOUBLE, TINYBLOB, TINYTEXT, MEDIUMBLOB, MEDIUMTEXT, LONGBLOB, LONGTEXT, ENUM, SET. etc. ― go by the wayside, because the agnostic capacities of scaffolding force us to translate our schema's objectives into generic, broader types.
For instance, we might usually create a given table with an SQL command:
CREATE TABLE amendments (id integer NOT NULL AUTO_INCREMENT PRIMARY KEY, c_code varchar(2), c_name varchar(35), tran_id integer, priority tinyint, created_at datetime, updated_at datetime, INDEX (id), FOREIGN KEY INDEX_tran_id (tran_id) REFERENCES translations (id) ON DELETE SET NULL ON UPDATE NO ACTION) ENGINE=InnoDB;
Unfortunately, scaffolding limitations compromise this command to the form of:
script/generate scaffold amendment c_code:string c_name:string tran_id:integer priority:integer.
Yes, the creation of the three id, created_at and updated_at fields is automated; but as you see, our intended varchar(2) field is degraded to a 'string' type, which ultimately translates to varchar(255).
Obviously, this degradation has potentially huge negative ramifications in our eventual implementation. Disk usage, throughput, and processing are redundantly degraded to huge degrees if we don't rectify the degraded definition for our tables to our purposed SQL schema definition.
Fortunately however, we can accomplish all the objects of preserving our purposed schema with a single line of code. Not finding models for the necessary procedure; instead finding resistance to 'prematurely optimizing' my approach to RoR (!); I thought it a good idea to simplify these issues for a possible minority (?) of coders who are likewise concerned with record design.
MODEL DEVELOPMENT PROCEDURE
1. Having already installed the MySQL gem (http://forums.mysql.com/read.php?116,359591,359591#msg-359591), we first create our MySQL project from the command line in terminal, according to usual convention:
rails myApp -d mysql
2. We next create our table definitions (.rb files in [project]/db/migrate/). For example:
script/generate scaffold amendment c_code:string c_name:string tran_id:integer priority:integer
3. BEFORE we create our databases or tables with 'rake db:create' and 'rake db:migrate' commands however, we now revise the table definitions in each .rb file:
3.a. Our 'script/generate scaffold' command resulted in the following .rb file:
class CreateAmendments < ActiveRecord::Migration
def self.up
create_table :amendments do t
t.string :c_code
t.string :c_name
t.integer :tran_id
t.integer :priority
t.timestamps
end
end
def self.down
drop_table :amendments
end
end
Yes. That's all we'll find there.
3.b. We want to revise the up method to create our table with actual SQL, using of course the very SQL we would invoke in observation of optimal practice:
class CreateAmendments < ActiveRecord::Migration
def self.up
execute 'CREATE TABLE amendments (id integer NOT NULL AUTO_INCREMENT PRIMARY KEY, c_code varchar(2), c_name varchar(35), tran_id integer, priority tinyint, created_at datetime, updated_at datetime, INDEX (id), FOREIGN KEY INDEX_tran_id (tran_id) REFERENCES translations (id) ON DELETE SET NULL ON UPDATE NO ACTION) ENGINE=InnoDB;'
end
def self.down
drop_table :amendments
end
end
As you see, we remember to create the necessary id, created_at, and updated_at fields ourselves.
Although it is desirable to set foreign keys this way, there's one caveat to doing so when your foreign key refers to a table which hasn't been created yet: the MySQL engine won't let us do this until the referenced table exists (you'll get a MySQL errno: 150). So, you either have to create your referenced tables first, or remove your foreign key references until all your tables are created. Once you've created the tables, you can restore the references, perform a migrate, and you're fine thereafter. In the case of later migrating your tables to test and production databases, you will have to take the same precautions of creation order. Comment out the execute statements of foreign keyed tables until the reference tables are created; whatever.
So, this specification, or any further modifications to this specification, will now preserve our intended table design across all further methods.
Should we modify the design schema, this is where we do it. In the course of further development, after further modifying a table design in this up method, you run 'rake db:migrate' to migrate the altered design across your development environment and/or deployment.
But of course, as we're just now building the application and its databases, we don't do this until we've completed the following steps.
4. Now we create our development database: rake db:create
5. And finally we create our tables: rake db:migrate
That's all there is to it.
Obviously, we restrict ourselves to incoherent designs without the SQL create statement in self.up. So, even for your first project, you want to get this under your belt, to never, never, never settle for anything less than optimal table designs ― rendered, migrated, and preserved by a single line of code.
Regards,
mike montagne
(C) Copyright, mike montagne, March 23, 2010
Edited 8 time(s). Last edit at 03/25/2010 09:36PM by mike montagne.

Options:Reply•Quote

Written By
Ruby, Rails and MySQL gem ― through scaffolding, versioning, rake db:create, db:migrate ― HOW to implement and preserve your schema with SQL
March 23, 2010 06:16PM

Rails Generate Scaffold With Foreign Key Set


Sorry, you can't reply to this topic. It has been closed.

Rails Generate Scaffold With Foreign Key Youtube

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.