- Rails Generate Scaffold With Foreign Key Code
- Rails Generate Scaffold With Foreign Key Set
- Rails Generate Scaffold With Foreign Key Examples
- Rails Generate Scaffold With Foreign Key Examples
This Guide is based on Rails 3.2. Some of the code shown here will notwork in earlier versions of Rails.
May 28, 2010 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'. Getting Started with Rails. This guide covers getting up and running with Ruby on Rails. After reading it, you should be familiar with. In previous versions of Rails, the rails generate scaffold command would automatically create a controller specific layout. The t.references line sets up a foreign key column for the association between. Feb 24, 2020 Command Line Generator Info Reference. You can get all of this information on the command line. Rails generate with no generator name will output a list of all available generators and some information about global options. Rails generate GENERATOR -help will list the options that can be passed to the specified generator. Rails Generate Examples. Railsで、modelにforeignkeyを指定した場合に、orderメソッドを使ってソートしたいです。 下記のようにユーザーと部署テーブルがあり、 ユーザーは部署に2つ所属する場合、. Welcome to Rails. Rails is a web-application framework that includes everything needed to create database-backed web applications according to the Model-View-Controller (MVC)pattern. Understanding the MVC pattern is key to understanding Rails.
1 Guide Assumptions
This guide is designed for beginners who want to get started with a Railsapplication from scratch. It does not assume that you have any prior experiencewith Rails. However, to get the most out of it, you need to have someprerequisites installed:
- The Ruby language version 1.8.7 or higher
Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails3.0 and above. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaultson Rails 3.0 and above, so if you want to use Rails 3.0 or above with 1.9.x jump on 1.9.2 for smoothsailing.
- The RubyGems packaging system
- If you want to learn more about RubyGems, please read the RubyGems User Guide
- A working installation of the SQLite3 Database
Rails is a web application framework running on the Ruby programming language.If you have no prior experience with Ruby, you will find a very steep learningcurve diving straight into Rails. There are some good free resources on theinternet for learning Ruby, including:
Also, the example code for this guide is available in the rails github:https://github.com/rails/rails repositoryin rails/railties/guides/code/getting_started.
2 What is Rails?
This section goes into the background and philosophy of the Rails frameworkin detail. You can safely skip this section and come back to it at a later time.Section 3 starts you on the path to creating your first Rails application.
Rails is a web application development framework written in the Ruby language.It is designed to make programming web applications easier by making assumptionsabout what every developer needs to get started. It allows you to write lesscode while accomplishing more than many other languages and frameworks.Experienced Rails developers also report that it makes web applicationdevelopment more fun.
Rails is opinionated software. It makes the assumption that there is a “best”way to do things, and it’s designed to encourage that way – and in some cases todiscourage alternatives. If you learn “The Rails Way” you’ll probably discover atremendous increase in productivity. If you persist in bringing old habits fromother languages to your Rails development, and trying to use patterns youlearned elsewhere, you may have a less happy experience.
The Rails philosophy includes several guiding principles:
- DRY – “Don’t Repeat Yourself” – suggests that writing the same code over and over again is a bad thing.
- Convention Over Configuration – means that Rails makes assumptions about what you want to do and how you’re going todo it, rather than requiring you to specify every little thing through endless configuration files.
- REST is the best pattern for web applications – organizing your application around resources and standard HTTP verbsis the fastest way to go.
2.1 The MVC Architecture
At the core of Rails is the Model, View, Controller architecture, usually justcalled MVC. MVC benefits include:
- Isolation of business logic from the user interface
- Ease of keeping code DRY
- Making it clear where different types of code belong for easier maintenance
2.1.1 Models
A model represents the information (data) of the application and the rules tomanipulate that data. In the case of Rails, models are primarily used formanaging the rules of interaction with a corresponding database table. In mostcases, each table in your database will correspond to one model in yourapplication. The bulk of your application’s business logic will be concentratedin the models.
2.1.2 Views
Views represent the user interface of your application. In Rails, views areoften HTML files with embedded Ruby code that perform tasks related solely tothe presentation of the data. Views handle the job of providing data to the webbrowser or other tool that is used to make requests from your application.
2.1.3 Controllers
Controllers provide the “glue” between models and views. In Rails, controllersare responsible for processing the incoming requests from the web browser,interrogating the models for data, and passing that data on to the views forpresentation.
2.2 The Components of Rails
Rails ships as many individual components. Each of these components are brieflyexplained below. If you are new to Rails, as you read this section, don’t gethung up on the details of each component, as they will be explained in furtherdetail later. For instance, we will bring up Rack applications, but you don’tneed to know anything about them to continue with this guide.
- Action Pack
- Action Controller
- Action Dispatch
- Action View
- Action Mailer
- Active Model
- Active Record
- Active Resource
- Active Support
- Railties
2.2.1 Action Pack
Action Pack is a single gem that contains Action Controller, Action View andAction Dispatch. The “VC” part of “MVC”.
2.2.1.1 Action Controller
Action Controller is the component that manages the controllers in a Railsapplication. The Action Controller framework processes incoming requests to aRails application, extracts parameters, and dispatches them to the intendedaction. Services provided by Action Controller include session management,template rendering, and redirect management.
2.2.1.2 Action View
Action View manages the views of your Rails application. It can create both HTMLand XML output by default. Action View manages rendering templates, includingnested and partial templates, and includes built-in AJAX support. Viewtemplates are covered in more detail in another guide called Layouts andRendering.
2.2.1.3 Action Dispatch
Action Dispatch handles routing of web requests and dispatches them as you want,either to your application or any other Rack application. Rack applications area more advanced topic and are covered in a separate guide called Rails onRack.
2.2.2 Action Mailer
Action Mailer is a framework for building e-mail services. You can use ActionMailer to receive and process incoming email and send simple plain text orcomplex multipart emails based on flexible templates.
2.2.3 Active Model
Active Model provides a defined interface between the Action Pack gem servicesand Object Relationship Mapping gems such as Active Record. Active Model allowsRails to utilize other ORM frameworks in place of Active Record if yourapplication needs this.
2.2.4 Active Record
Active Record is the base for the models in a Rails application. It providesdatabase independence, basic CRUD functionality, advanced finding capabilities,and the ability to relate models to one another, among other services.
2.2.5 Active Resource
Active Resource provides a framework for managing the connection betweenbusiness objects and RESTful web services. It implements a way to map web-basedresources to local objects with CRUD semantics.
2.2.6 Active Support
Active Support is an extensive collection of utility classes and standard Rubylibrary extensions that are used in Rails, both by the core code and by yourapplications.
2.2.7 Railties
Railties is the core Rails code that builds new Rails applications and glues thevarious frameworks and plugins together in any Rails application.
2.3 REST
Rest stands for Representational State Transfer and is the foundation of theRESTful architecture. This is generally considered to be Roy Fielding’s doctoralthesis, Architectural Styles and the Design of Network-based SoftwareArchitectures. Whileyou can read through the thesis, REST in terms of Rails boils down to two mainprinciples:
- Using resource identifiers such as URLs to represent resources.
- Transferring representations of the state of that resource between system components.
For example, the following HTTP request:
DELETE /photos/17
would be understood to refer to a photo resource with the ID of 17, and toindicate a desired action – deleting that resource. REST is a natural style forthe architecture of web applications, and Rails hooks into this shielding youfrom many of the RESTful complexities and browser quirks.
If you’d like more details on REST as an architectural style, these resourcesare more approachable than Fielding’s thesis:
- A Brief Introduction to REST by Stefan Tilkov
- An Introduction to REST (video tutorial) by Joe Gregorio
- Representational State Transfer article in Wikipedia
- How to GET a Cup of Coffee by Jim Webber, Savas Parastatidis &Ian Robinson
3 Creating a New Rails Project
The best way to use this guide is to follow each step as it happens, no code orstep needed to make this example application has been left out, so you canliterally follow along step by step. You can get the complete code here.
By following along with this guide, you’ll create a Rails project called blog, a(very) simple weblog. Before you can start building the application, you need tomake sure that you have Rails itself installed.
The examples below use # and $ to denote terminal prompts. If you are using Windows, your prompt will look something like c:source_code>
3.1 Installing Rails
In most cases, the easiest way to install Rails is to take advantage of RubyGems:
If you’re working on Windows, you can quickly install Ruby and Rails withRails Installer.
To verify that you have everything installed correctly, you should be able to runthe following:
If it says something like “Rails 3.2.3” you are ready to continue.
3.2 Creating the Blog Application
To begin, open a terminal, navigate to a folder where you have rights to createfiles, and type:
This will create a Rails application called Blog in a directory called blog.
You can see all of the switches that the Rails application builder acceptsby runningrails new -h.
After you create the blog application, switch to its folder to continue workdirectly in that application:
The ‘rails new blog’ command we ran above created a folder in your working directorycalled blog. The blog folder has a number of auto-generated foldersthat make up the structure of a Rails application. Most of the work inthis tutorial will happen in the app/ folder, but here’s a basicrundown on the function of each of the files and folders that Rails created by default:
File/Folder | Purpose |
---|---|
app/ | Contains the controllers, models, views and assets for your application. You’ll focus on this folder for the remainder of this guide. |
config/ | Configure your application’s runtime rules, routes, database, and more. This is covered in more detail in Configuring Rails Applications |
config.ru | Rack configuration for Rack based servers used to start the application. |
db/ | Contains your current database schema, as well as the database migrations. |
doc/ | In-depth documentation for your application. |
Gemfile Gemfile.lock | These files allow you to specify what gem dependencies are needed for your Rails application. |
lib/ | Extended modules for your application. |
log/ | Application log files. |
public/ | The only folder seen to the world as-is. Contains the static files and compiled assets. |
Rakefile | This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application. |
README.rdoc | This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on. |
script/ | Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application. |
test/ | Unit tests, fixtures, and other test apparatus. These are covered in Testing Rails Applications |
tmp/ | Temporary files |
vendor/ | A place for all third-party code. In a typical Rails application, this includes Ruby Gems, the Rails source code (if you optionally install it into your project) and plugins containing additional prepackaged functionality. |
3.3 Configuring a Database
Just about every Rails application will interact with a database. The databaseto use is specified in a configuration file, config/database.yml. If you openthis file in a new Rails application, you’ll see a default databaseconfigured to use SQLite3. The file contains sections for three differentenvironments in which Rails can run by default:
- The development environment is used on your development/local computer as you interactmanually with the application.
- The test environment is used when running automated tests.
- The production environment is used when you deploy your application for the world to use.
You don’t have to update the database configurations manually. If you look at theoptions of the application generator, you will see that one of the optionsis named —database. This option allows you to choose an adapter from alist of the most used relational databases. You can even run the generatorrepeatedly: cd .. && rails new blog —database=mysql. When you confirm the overwriting of the config/database.yml file, your application will be configured for MySQLinstead of SQLite. Detailed examples of the common database connections are below.
3.3.1 Configuring an SQLite3 Database
Rails comes with built-in support for SQLite3, which isa lightweight serverless database application. While a busy productionenvironment may overload SQLite, it works well for development and testing.Rails defaults to using an SQLite database when creating a new project, but youcan always change it later.
Here’s the section of the default configuration file(config/database.yml) with connection information for the developmentenvironment:
In this guide we are using an SQLite3 database for data storage, becauseit is a zero configuration database that just works. Rails also supports MySQLand PostgreSQL “out of the box”, and has plugins for many database systems. Ifyou are using a database in a production environment Rails most likely has anadapter for it.
3.3.2 Configuring a MySQL Database
If you choose to use MySQL instead of the shipped SQLite3 database, yourconfig/database.yml will look a little different. Here’s the developmentsection:
If your development computer’s MySQL installation includes a root user with anempty password, this configuration should work for you. Otherwise, change theusername and password in the development section as appropriate.
3.3.3 Configuring a PostgreSQL Database
If you choose to use PostgreSQL, your config/database.yml will be customizedto use PostgreSQL databases:
3.3.4 Configuring an SQLite3 Database for JRuby Platform
If you choose to use SQLite3 and are using JRuby, your config/database.yml willlook a little different. Here’s the development section:
3.3.5 Configuring a MySQL Database for JRuby Platform
If you choose to use MySQL and are using JRuby, your config/database.yml will looka little different. Here’s the development section:
3.3.6 Configuring a PostgreSQL Database for JRuby Platform
Finally if you choose to use PostgreSQL and are using JRuby, yourconfig/database.yml will look a little different. Here’s the developmentsection:
Change the username and password in the development section as appropriate.
3.4 Creating the Database
Now that you have your database configured, it’s time to have Rails create anempty database for you. You can do this by running a rake command:
This will create your development and test SQLite3 databases inside thedb/ folder.
Rake is a general-purpose command-runner that Rails uses for many things.You can see the list of available rake commands in your application by runningrake -T.
4 Hello, Rails!
One of the traditional places to start with a new language is by getting sometext up on screen quickly. To do this, you need to get your Rails applicationserver running.
4.1 Starting up the Web Server
You actually have a functional Rails application already. To see it, you need tostart a web server on your development machine. You can do this by running:
Compiling CoffeeScript to JavaScript requires a JavaScript runtime andthe absence of a runtime will give you an execjs error. Usually Mac OS Xand Windows come with a JavaScript runtime installed. Rails adds the therubyracer gemto Gemfile in a commented line for new apps and you can uncomment if you need it.therubyrhino is the recommended runtime for JRuby users and is added by defaultto Gemfile in apps generated under JRuby. You can investigate about all thesupported runtimes at ExecJS.
This will fire up an instance of the WEBrick web server by default (Rails canalso use several other web servers). To see your application in action, open abrowser window and navigate to http://localhost:3000.You should see Rails’ default information page:
To stop the web server, hit Ctrl+C in the terminal window where it’srunning. In development mode, Rails does not generally require you to stop theserver; changes you make in files will be automatically picked up by the server.
The “Welcome Aboard” page is the smoke test for a new Rails application: itmakes sure that you have your software configured correctly enough to serve apage. You can also click on the About your application’s environment link tosee a summary of your application’s environment.
4.2 Say “Hello”, Rails
To get Rails saying “Hello”, you need to create at minimum a controller and aview. Fortunately, you can do that in a single command. Enter this command inyour terminal:
If you get a command not found error when running this command, youneed to explicitly pass Rails rails commands to Ruby: rubypathtoyourapplicationscriptrails generate controller home index.
Rails will create several files for you, includingapp/views/home/index.html.erb. This is the template that will be used todisplay the results of the index action (method) in the home controller.Open this file in your text editor and edit it to contain a single line of code:
<h1>Hello, Rails!</h1>
4.3 Setting the Application Home Page
Now that we have made the controller and view, we need to tell Rails when wewant “Hello Rails!” to show up. In our case, we want it to show up when wenavigate to the root URL of our site,http://localhost:3000, instead of the “Welcome Aboard”smoke test.
The first step to doing this is to delete the default page from yourapplication:
We need to do this as Rails will deliver any static file in the publicdirectory in preference to any dynamic content we generate from the controllers.
Now, you have to tell Rails where your actual home page is located. Open thefile config/routes.rb in your editor. This is your application’s routingfile which holds entries in a special DSL (domain-specific language) that tellsRails how to connect incoming requests to controllers and actions. This filecontains many sample routes on commented lines, and one of them actually showsyou how to connect the root of your site to a specific controller and action.Find the line beginning with root :to and uncomment it. It should look something like the following:
The root :to => 'home#index' tells Rails to map the root action to the homecontroller’s index action.
Now if you navigate to http://localhost:3000 in yourbrowser, you’ll see Hello, Rails!.
For more information about routing, refer to Rails Routing from theOutside In.
5 Getting Up and Running Quickly with Scaffolding
Rails scaffolding is a quick way to generate some of the major pieces of anapplication. If you want to create the models, views, and controllers for a newresource in a single operation, scaffolding is the tool for the job.
6 Creating a Resource
In the case of the blog application, you can start by generating a scaffold for thePost resource: this will represent a single blog posting. To do this, enter thiscommand in your terminal:
The scaffold generator will build several files in your application, along with somefolders, and edit config/routes.rb. Here’s a quick overview of what it creates:
File | Purpose |
---|---|
db/migrate/20100207214725_create_posts.rb | Migration to create the posts table in your database (your name will include a different timestamp) |
app/models/post.rb | The Post model |
test/unit/post_test.rb | Unit testing harness for the posts model |
test/fixtures/posts.yml | Sample posts for use in testing |
config/routes.rb | Edited to include routing information for posts |
app/controllers/posts_controller.rb | The Posts controller |
app/views/posts/index.html.erb | A view to display an index of all posts |
app/views/posts/edit.html.erb | A view to edit an existing post |
app/views/posts/show.html.erb | A view to display a single post |
app/views/posts/new.html.erb | A view to create a new post |
app/views/posts/_form.html.erb | A partial to control the overall look and feel of the form used in edit and new views |
test/functional/posts_controller_test.rb | Functional testing harness for the posts controller |
app/helpers/posts_helper.rb | Helper functions to be used from the post views |
test/unit/helpers/posts_helper_test.rb | Unit testing harness for the posts helper |
app/assets/javascripts/posts.js.coffee | CoffeeScript for the posts controller |
app/assets/stylesheets/posts.css.scss | Cascading style sheet for the posts controller |
app/assets/stylesheets/scaffolds.css.scss | Cascading style sheet to make the scaffolded views look better |
While scaffolding will get you up and running quickly, the code itgenerates is unlikely to be a perfect fit for your application. You’ll mostprobably want to customize the generated code. Many experienced Rails developersavoid scaffolding entirely, preferring to write all or most of their source codefrom scratch. Rails, however, makes it really simple to customize templates forgenerated models, controllers, views and other source files. You’ll find moreinformation in the Creating and Customizing Rails Generators &Templates guide.
6.1 Running a Migration
One of the products of the rails generate scaffold command is a databasemigration. Migrations are Ruby classes that are designed to make it simple tocreate and modify database tables. Rails uses rake commands to run migrations,and it’s possible to undo a migration after it’s been applied to your database.Migration filenames include a timestamp to ensure that they’re processed in theorder that they were created.
If you look in the db/migrate/20100207214725_create_posts.rb file (remember,yours will have a slightly different name), here’s what you’ll find:
The above migration creates a method named change which will be called when yourun this migration. The action defined in this method is also reversible, whichmeans Rails knows how to reverse the change made by this migration, in case youwant to reverse it later. When you run this migration it will create aposts table with two string columns and a text column. It also creates twotimestamp fields to allow Rails to track post creation and update times. Moreinformation about Rails migrations can be found in the Rails DatabaseMigrations guide.
At this point, you can use a rake command to run the migration:
Rails will execute this migration command and tell you it created the Poststable.
Because you’re working in the development environment by default, thiscommand will apply to the database defined in the development section of yourconfig/database.yml file. If you would like to execute migrations in anotherenvironment, for instance in production, you must explicitly pass it wheninvoking the command: rake db:migrate RAILS_ENV=production.
6.2 Adding a Link
To hook the posts up to the home page you’ve already created, you can add a linkto the home page. Open app/views/home/index.html.erb and modify it as follows:
The link_to method is one of Rails’ built-in view helpers. It creates ahyperlink based on text to display and where to go – in this case, to the pathfor posts.
6.3 Working with Posts in the Browser
Now you’re ready to start working with posts. To do that, navigate tohttp://localhost:3000 and then click the “My Blog”link:
This is the result of Rails rendering the index view of your posts. Therearen’t currently any posts in the database, but if you click the New Post linkyou can create one. After that, you’ll find that you can edit posts, look attheir details, or destroy them. All of the logic and HTML to handle this wasbuilt by the single rails generate scaffold command.
In development mode (which is what you’re working in by default), Railsreloads your application with every browser request, so there’s no need to stopand restart the web server.
Congratulations, you’re riding the rails! Now it’s time to see how it all works.
6.4 The Model
The model file, app/models/post.rb is about as simple as it can get:
There isn’t much to this file – but note that the Post class inherits fromActiveRecord::Base. Active Record supplies a great deal of functionality toyour Rails models for free, including basic database CRUD (Create, Read, Update,Destroy) operations, data validation, as well as sophisticated search supportand the ability to relate multiple models to one another. Another important partof this file is attr_accessible. It specifies a whitelist of attributes that areallowed to be updated in bulk (via update_attributes for instance).
6.5 Adding Some Validation
Rails includes methods to help you validate the data that you send to models.Open the app/models/post.rb file and edit it:
These changes will ensure that all posts have a name and a title, and that thetitle is at least five characters long. Rails can validate a variety ofconditions in a model, including the presence or uniqueness of columns, theirformat, and the existence of associated objects. Validations are covered in detailin Active Record Validations and Callbacks
6.6 Using the Console
To see your validations in action, you can use the console. The console is acommand-line tool that lets you execute Ruby code in the context of yourapplication:
The default console will make changes to your database. You can insteadopen a console that will roll back any changes you make by using rails console—sandbox.
After the console loads, you can use it to work with your application’s models:
This code shows creating a new Post instance, attempting to save it andgetting false for a return value (indicating that the save failed), andinspecting the errors of the post.
When you’re finished, type exit and hit return to exit the console.
Unlike the development web server, the console does not automatically loadyour code afresh for each line. If you make changes to your models (in your editor)while the console is open, type reload! at the console prompt to load them.
6.7 Listing All Posts
Let’s dive into the Rails code a little deeper to see how the application isshowing us the list of Posts. Open the fileapp/controllers/posts_controller.rb and look at theindex action:
Post.all returns all of the posts currently in the database as an arrayof Post records that we store in an instance variable called @posts.
For more information on finding records with Active Record, see ActiveRecord Query Interface.
The respond_to block handles both HTML and JSON calls to this action. If youbrowse to http://localhost:3000/posts.json,you’ll see a JSON containing all of the posts. The HTML format looks for a viewin app/views/posts/ with a name that corresponds to the action name. Railsmakes all of the instance variables from the action available to the view.Here’s app/views/posts/index.html.erb:
This view iterates over the contents of the @posts array to display contentand links. A few things to note in the view:
- link_to builds a hyperlink to a particular destination
- edit_post_path and new_post_path are helpers that Rails provides as part of RESTful routing. You’ll see a variety of these helpers for the different actions that the controller includes.
In previous versions of Rails, you had to use <%=h post.name %> sothat any HTML would be escaped before being inserted into the page. In Rails3 and above, this is now the default. To get unescaped HTML, you now use <%= raw post.name %>.
For more details on the rendering process, see Layouts and Rendering inRails.
6.8 Customizing the Layout
The view is only part of the story of how HTML is displayed in your web browser.Rails also has the concept of layouts, which are containers for views. WhenRails renders a view to the browser, it does so by putting the view’s HTML intoa layout’s HTML. In previous versions of Rails, the rails generate scaffoldcommand would automatically create a controller specific layout, likeapp/views/layouts/posts.html.erb, for the posts controller. However this hasbeen changed in Rails 3. An application specific layout is used for all thecontrollers and can be found in app/views/layouts/application.html.erb. Openthis layout in your editor and modify the body tag to include the style directivebelow:
Now when you refresh the /posts page, you’ll see a gray background to thepage. This same gray background will be used throughout all the views for posts.
6.9 Creating New Posts
Creating a new post involves two actions. The first is the new action, whichinstantiates an empty Post object:
The new.html.erb view displays this empty Post to the user:
The <%= render 'form' %> line is our first introduction to partials inRails. A partial is a snippet of HTML and Ruby code that can be reused inmultiple locations. In this case, the form used to make a new post is basicallyidentical to the form used to edit a post, both having text fields for the name andtitle, a text area for the content, and a button to create the new post or to updatethe existing one.
If you take a look at views/posts/_form.html.erb file, you will see thefollowing:
![Foreign Foreign](/uploads/1/2/5/8/125876252/748240649.png)
This partial receives all the instance variables defined in the calling viewfile. In this case, the controller assigned the new Post object to @post,which will thus be available in both the view and the partial as @post.
For more information on partials, refer to the Layouts and Rendering inRails guide.
The form_for block is used to create an HTML form. Within this block, you haveaccess to methods to build various controls on the form. For example,f.text_field :name tells Rails to create a text input on the form and to hookit up to the name attribute of the instance being displayed. You can only usethese methods with attributes of the model that the form is based on (in thiscase name, title, and content). Rails uses form_for in preference tohaving you write raw HTML because the code is more succinct, and because itexplicitly ties the form to a particular model instance.
The form_for block is also smart enough to work out if you are doing a NewPost or an Edit Post action, and will set the form action tags and submitbutton names appropriately in the HTML output.
If you need to create an HTML form that displays arbitrary fields, not tiedto a model, you should use the form_tag method, which provides shortcuts forbuilding forms that are not necessarily tied to a model instance.
When the user clicks the Create Post button on this form, the browser willsend information back to the create action of the controller (Rails knows tocall the create action because the form is sent with an HTTPPOST request;that’s one of the conventions that were mentioned earlier):
The create action instantiates a new Post object from the data supplied by theuser on the form, which Rails makes available in the params hash. Aftersuccessfully saving the new post, create returns the appropriate format thatthe user has requested (HTML in our case). It then redirects the user to theresulting post show action and sets a notice to the user that the Post wassuccessfully created.
If the post was not successfully saved, due to a validation error, then thecontroller returns the user back to the new action with any error messages sothat the user has the chance to fix the error and try again.
The “Post was successfully created.” message is stored in the Railsflash hash (usually just called the flash), so that messages can be carriedover to another action, providing the user with useful information on the statusof their request. In the case of create, the user never actually sees any pagerendered during the post creation process, because it immediately redirects tothe new Post as soon as Rails saves the record. The Flash carries over a message tothe next action, so that when the user is redirected back to the show action,they are presented with a message saying “Post was successfully created.”
6.10 Showing an Individual Post
When you click the show link for a post on the index page, it will bring youto a URL like http://localhost:3000/posts/1. Rails interprets this as a callto the show action for the resource, and passes in 1 as the :id parameter.Here’s the show action:
The show action uses Post.find to search for a single record in the databaseby its id value. After finding the record, Rails displays it by usingapp/views/posts/show.html.erb:
6.11 Editing Posts
Like creating a new post, editing a post is a two-part process. The first stepis a request to edit_post_path(@post) with a particular post. This calls theedit action in the controller:
After finding the requested post, Rails uses the edit.html.erb view to displayit:
Again, as with the new action, the edit action is using the form partial.This time, however, the form will do a PUT action to the PostsController and thesubmit button will display “Update Post”.
Submitting the form created by this view will invoke the update action withinthe controller:
In the update action, Rails first uses the :id parameter passed back fromthe edit view to locate the database record that’s being edited. Theupdate_attributes call then takes the post parameter (a hash) from the requestand applies it to this record. If all goes well, the user is redirected to thepost’s show action. If there are any problems, it redirects back to the edit action tocorrect them.
6.12 Destroying a Post
Finally, clicking one of the destroy links sends the associated id to thedestroy action:
The destroy method of an Active Record model instance removes thecorresponding record from the database. After that’s done, there isn’t anyrecord to display, so Rails redirects the user’s browser to the index action ofthe controller.
7 Adding a Second Model
Now that you’ve seen what a model built with scaffolding looks like, it’s time toadd a second model to the application. The second model will handle comments onblog posts.
7.1 Generating a Model
Models in Rails use a singular name, and their corresponding database tables usea plural name. For the model to hold comments, the convention is to use the nameComment. Even if you don’t want to use the entire apparatus set up byscaffolding, most Rails developers still use generators to make things likemodels and controllers. To create the new model, run this command in yourterminal:
This command will generate four files:
File | Purpose |
---|---|
db/migrate/20100207235629_create_comments.rb | Migration to create the comments table in your database (your name will include a different timestamp) |
app/models/comment.rb | The Comment model |
test/unit/comment_test.rb | Unit testing harness for the comments model |
test/fixtures/comments.yml | Sample comments for use in testing |
First, take a look at comment.rb:
This is very similar to the post.rb model that you saw earlier. The differenceis the line belongs_to :post, which sets up an Active Record association.You’ll learn a little about associations in the next section of this guide.
In addition to the model, Rails has also made a migration to create thecorresponding database table:
The t.references line sets up a foreign key column for the association betweenthe two models. And the add_index line sets up an index for this associationcolumn. Go ahead and run the migration:
Rails is smart enough to only execute the migrations that have not already beenrun against the current database, so in this case you will just see:
7.2 Associating Models
Active Record associations let you easily declare the relationship between twomodels. In the case of comments and posts, you could write out the relationshipsthis way:
- Each comment belongs to one post.
- One post can have many comments.
In fact, this is very close to the syntax that Rails uses to declare thisassociation. You’ve already seen the line of code inside the Comment model thatmakes each comment belong to a Post:
You’ll need to edit the post.rb file to add the other side of the association:
These two declarations enable a good bit of automatic behavior. For example, ifyou have an instance variable @post containing a post, you can retrieve allthe comments belonging to that post as an array using @post.comments.
For more information on Active Record associations, see the Active RecordAssociations guide.
7.3 Adding a Route for Comments
As with the home controller, we will need to add a route so that Rails knowswhere we would like to navigate to see comments. Open up theconfig/routes.rb file again. Near the top, you will see the entry for poststhat was added automatically by the scaffold generator: resources:posts. Edit it as follows:
This creates comments as a nested resource within posts. This is anotherpart of capturing the hierarchical relationship that exists between posts andcomments.
For more information on routing, see the Rails Routing from the OutsideIn guide.
7.4 Generating a Controller
With the model in hand, you can turn your attention to creating a matchingcontroller. Again, there’s a generator for this:
This creates six files and one empty directory:
File/Directory | Purpose |
---|---|
app/controllers/comments_controller.rb | The Comments controller |
app/views/comments/ | Views of the controller are stored here |
test/functional/comments_controller_test.rb | The functional tests for the controller |
app/helpers/comments_helper.rb | A view helper file |
test/unit/helpers/comments_helper_test.rb | The unit tests for the helper |
app/assets/javascripts/comment.js.coffee | CoffeeScript for the controller |
app/assets/stylesheets/comment.css.scss | Cascading style sheet for the controller |
Like with any blog, our readers will create their comments directly afterreading the post, and once they have added their comment, will be sent back tothe post show page to see their comment now listed. Due to this, ourCommentsController is there to provide a method to create comments and deletespam comments when they arrive.
So first, we’ll wire up the Post show template(/app/views/posts/show.html.erb) to let us make a new comment:
This adds a form on the Post show page that creates a new comment bycalling the CommentsControllercreate action. Let’s wire that up:
You’ll see a bit more complexity here than you did in the controller for posts.That’s a side-effect of the nesting that you’ve set up. Each request for acomment has to keep track of the post to which the comment is attached, thus theinitial call to the find method of the Post model to get the post in question.
In addition, the code takes advantage of some of the methods available for anassociation. We use the create method on @post.comments to create and savethe comment. This will automatically link the comment so that it belongs to thatparticular post.
Once we have made the new comment, we send the user back to the original postusing the post_path(@post) helper. As we have already seen, this calls theshow action of the PostsController which in turn renders the show.html.erbtemplate. This is where we want the comment to show, so let’s add that to theapp/views/posts/show.html.erb.
Now you can add posts and comments to your blog and have them show up in theright places.
8 Refactoring
Now that we have posts and comments working, take a look at theapp/views/posts/show.html.erb template. It is getting long and awkward. We canuse partials to clean it up.
Rails Generate Scaffold With Foreign Key Code
8.1 Rendering Partial Collections
First we will make a comment partial to extract showing all the comments for thepost. Create the file app/views/comments/_comment.html.erb and put thefollowing into it:
Then you can change app/views/posts/show.html.erb to look like thefollowing:
This will now render the partial in app/views/comments/_comment.html.erb oncefor each comment that is in the @post.comments collection. As the rendermethod iterates over the @post.comments collection, it assigns eachcomment to a local variable named the same as the partial, in this casecomment which is then available in the partial for us to show.
8.2 Rendering a Partial Form
Let us also move that new comment section out to its own partial. Again, youcreate a file app/views/comments/_form.html.erb containing:
Then you make the app/views/posts/show.html.erb look like the following:
The second render just defines the partial template we want to render,comments/form. Rails is smart enough to spot the forward slash in thatstring and realize that you want to render the _form.html.erb file inthe app/views/comments directory.
The @post object is available to any partials rendered in the view because wedefined it as an instance variable.
9 Deleting Comments
Another important feature of a blog is being able to delete spam comments. To dothis, we need to implement a link of some sort in the view and a DELETE actionin the CommentsController.
So first, let’s add the delete link in theapp/views/comments/_comment.html.erb partial:
Clicking this new “Destroy Comment” link will fire off a DELETE/posts/:id/comments/:id to our CommentsController, which can then usethis to find the comment we want to delete, so let’s add a destroy action to ourcontroller:
The destroy action will find the post we are looking at, locate the commentwithin the @post.comments collection, and then remove it from thedatabase and send us back to the show action for the post.
9.1 Deleting Associated Objects
If you delete a post then its associated comments will also need to be deleted.Otherwise they would simply occupy space in the database. Rails allows you touse the dependent option of an association to achieve this. Modify the Postmodel, app/models/post.rb, as follows:
10 Security
If you were to publish your blog online, anybody would be able to add, edit anddelete posts or delete comments.
Rails provides a very simple HTTP authentication system that will work nicely inthis situation.
In the PostsController we need to have a way to block access to the variousactions if the person is not authenticated, here we can use the Railshttp_basic_authenticate_with method, allowing access to the requestedaction if that method allows it.
To use the authentication system, we specify it at the top of ourPostsController, in this case, we want the user to be authenticated on everyaction, except for index and show, so we write that:
We also only want to allow authenticated users to delete comments, so in theCommentsController we write:
Now if you try to create a new post, you will be greeted with a basic HTTPAuthentication challenge
11 Building a Multi-Model Form
Another feature of your average blog is the ability to tag posts. To implementthis feature your application needs to interact with more than one model on asingle form. Rails offers support for nested forms.
To demonstrate this, we will add support for giving each post multiple tags,right in the form where you create the post. First, create a new model to holdthe tags:
Again, run the migration to create the database table:
Next, edit the post.rb file to create the other side of the association, andto tell Rails (via the accepts_nested_attributes_for macro) that you intend toedit tags via posts:
The :allow_destroy option tells Rails to enable destroying tags through thenested attributes (you’ll handle that by displaying a “remove” checkbox on theview that you’ll build shortly). The :reject_if option prevents saving newtags that do not have any attributes filled in.
Also note we had to add :tags_attributes to the attr_accessible list. Ifwe didn’t do this there would be a MassAssignmentSecurity exception when we try toupdate tags through our posts model.
We will modify views/posts/_form.html.erb to render a partial to make a tag:
Note that we have changed the f in form_for(@post) do |f| to post_form tomake it easier to understand what is going on.
This example shows another option of the render helper, being able to pass inlocal variables, in this case, we want the local variable form in the partialto refer to the post_form object.
We also add a @post.tags.build at the top of this form. This is to makesure there is a new tag ready to have its name filled in by the user. If you donot build the new tag, then the form will not appear as there is no new Tagobject ready to create.
Now create the folder app/views/tags and make a file in there called_form.html.erb which contains the form for the tag:
Finally, we will edit the app/views/posts/show.html.erb template toshow our tags.
With these changes in place, you’ll find that you can edit a post and its tagsdirectly on the same view.
However, that method call @post.tags.map { |t| t.name }.join(', ') isawkward, we could handle this by making a helper method.
12 View Helpers
View Helpers live in app/helpers and provide small snippets of reusablecode for views. In our case, we want a method that strings a bunch of objectstogether using their name attribute and joining them with a comma. As this isfor the Post show template, we put it in the PostsHelper.
Open up app/helpers/posts_helper.rb and add the following:
Now you can edit the view in app/views/posts/show.html.erb to look likethis:
13 What’s Next?
Now that you’ve seen your first Rails application, you should feel free toupdate it and experiment on your own. But you don’t have to do everythingwithout help. As you need assistance getting up and running with Rails, feelfree to consult these support resources:
- The Ruby on Rails guides
- The Ruby on Rails Tutorial
- The Ruby on Rails mailing list
- The #rubyonrails channel on irc.freenode.net
Rails also comes with built-in help that you can generate using the rake command-line utility:
- Running rake doc:guides will put a full copy of the Rails Guides in the doc/guides folder of your application. Open doc/guides/index.html in your web browser to explore the Guides.
- Running rake doc:rails will put a full copy of the API documentation for Rails in the doc/api folder of your application. Open doc/api/index.html in your web browser to explore the API documentation.
14 Configuration Gotchas
The easiest way to work with Rails is to store all external data as UTF-8. Ifyou don’t, Ruby libraries and Rails will often be able to convert your nativedata into UTF-8, but this doesn’t always work reliably, so you’re better offensuring that all external data is UTF-8.
If you have made a mistake in this area, the most common symptom is a blackdiamond with a question mark inside appearing in the browser. Another commonsymptom is characters like “ü” appearing instead of “ü”. Rails takes a numberof internal steps to mitigate common causes of these problems that can beautomatically detected and corrected. However, if you have external data that isnot stored as UTF-8, it can occasionally result in these kinds of issues thatcannot be automatically detected by Rails and corrected.
Two very common sources of data that are not UTF-8:
- Your text editor: Most text editors (such as Textmate), default to saving files as UTF-8. If your text editor does not, this can result in special characters that you enter in your templates (such as é) to appear as a diamond with a question mark inside in the browser. This also applies to your I18N translation files. Most editors that do not already default to UTF-8 (such as some versions of Dreamweaver) offer a way to change the default to UTF-8. Do so.
- Your database. Rails defaults to converting data from your database into UTF-8 at the boundary. However, if your database is not using UTF-8 internally, it may not be able to store all characters that your users enter. For instance, if your database is using Latin-1 internally, and your user enters a Russian, Hebrew, or Japanese character, the data will be lost forever once it enters the database. If possible, use UTF-8 as the internal storage of your database.
Feedback
You're encouraged to help improve the quality of this guide.
If you see any typos or factual errors you are confident to patch, please clone docrails and push the change yourself. That branch of Rails has public write access. Commits are still reviewed, but that happens after you've submitted your contribution. docrails is cross-merged with master periodically.
You may also find incomplete content, or stuff that is not up to date. Please do add any missing documentation for master. 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 in the rubyonrails-docs mailing list.
This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.
1 Command Line Basics
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:
rails console
rails server
rails test
rails generate
rails db:migrate
rails db:create
rails routes
rails dbconsole
rails new app_name
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: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
):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 Generate Scaffold With Foreign Key Set
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
clearstmp/cache
.rails tmp:sockets:clear
clearstmp/sockets
.rails tmp:screenshots:clear
clearstmp/screenshots
.rails tmp:clear
clears all cache, sockets, and screenshot files.rails tmp:create
creates tmp directories for cache, sockets, and pids.
Rails Generate Scaffold With Foreign Key Examples
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.
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:
Rails Generate Scaffold With Foreign Key Examples
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. 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.