Ruby on Rails入门经典+实例
- 格式:ppt
- 大小:1.15 MB
- 文档页数:31


Ruby on Rails在Web开发中的应用分享Web开发技术一直在不断地发展和演变,框架也不断涌现,其中最著名之一便是Ruby on Rails。
Ruby on Rails是一款基于Ruby 语言的Web开发框架,也叫做Rails。
它能够让开发者用更少的代码实现更多功能,并且提供了一整套简单易用的解决方案,使得开发效率和开发体验都得到了很大的提升。
在我们的工作中,我们经常会用到Ruby on Rails来开发不同类型的Web应用。
一、简介Ruby on Rails是由David Heinemeier Hansson所开发的Web开发框架,其旨在提高开发效率和开发体验,使得开发人员能够更加专注于业务逻辑的实现。
Ruby on Rails建立在一系列优秀的基础库之上,如ActiveRecord、ActionPack等,这些库能够极大地简化开发过程。
二、 Ruby on Rails的优势Ruby on Rails作为一款Web开发框架,具有以下几个优势:1.简单易用Rails提供了一整套简单易用的开发解决方案,使得开发者能够快速地进行开发,减少了开发的复杂性。
例如,Rails的MVC框架就能够用更加优雅的方式描述应用程序的结构,模型文件中也能够定义关系更加清晰。
2.丰富的文档Rails拥有丰富的文档,使得开发者能够很容易地找到需要的信息,学习框架所需的时间大大缩短。
Rails的官方文档也很不错,配合社区的文档使用,可以让开发者很好地掌握框架的使用。
3.良好的扩展性Rails拥有良好的扩展性,使得开发者可以自由地添加自己的功能和组件。
Rails拥有大量的插件和扩展,可以满足开发者各种各样的需求。
4.高效率Rails的许多功能都可以通过使用代码生成器来快速生成,大大提高了开发效率。
此外,Rails强烈推荐使用测试驱动开发,使得代码更加可靠,开发人员也可以更加自信地进行开发和维护。
三、 Ruby on Rails的应用场景Rails有很多应用场景,包括但不限于:1.电子商务网站:Rails拥有很强的ORM功能,使得它很好地支持大规模的数据操作。
学会使用Ruby on Rails进行Web开发Web开发是当今技术领域的热门话题之一。
在互联网的时代,几乎每个人都希望能够掌握一些Web开发的基础知识。
而Ruby on Rails (简称Rails)作为一种流行的开发框架,成为了众多开发者学习的首选。
本文将介绍Rails的一些基本特性和使用技巧,帮助初学者快速入门Web开发。
1. 起步获取Rails最简单的方式是通过Ruby的包管理器gem安装,只需要在终端输入一行命令即可:```gem install rails```安装完成后,使用以下命令创建一个新的Rails项目:```rails new myapp```这会在当前目录下创建一个名为`myapp`的Rails应用。
2. MVC架构Rails遵循MVC (Model-View-Controller)架构模式,将应用分为三个主要组件:模型、视图和控制器。
这种架构模式使得代码的组织和维护更加清晰和高效。
- 模型(Model):主要负责处理数据逻辑和数据库操作。
在Rails中,可以使用Active Record来建立模型和数据库表之间的映射关系。
- 视图(View):负责展示数据给用户。
Rails使用ERB(Embedded Ruby)作为默认的模板语言,可以方便地将Ruby代码嵌入到HTML中。
- 控制器(Controller):接收用户的请求并处理相应的逻辑。
Rails的控制器和路由系统能够将请求映射到相应的控制器动作上。
3. 数据库操作Rails提供了丰富的数据库操作方式,可以轻松地进行数据的增删改查。
在Rails中,可以使用Active Record提供的方法来操作数据库。
例如,要获取所有用户的数据,只需要在控制器中调用以下方法:```ruby@users = User.all```然后在视图中通过循环来展示这些数据:```erb<% @users.each do |user| %><p><%= %></p><% end %>```此外,Rails还提供了便捷的方式来处理数据的验证、关联和查询等操作,让开发者能够更加高效地操作数据库。
About the T utorialRuby on Rails is an extremely productive web application framework written in Ruby by David Heinemeier Hansson. This tutorial gives you a complete understanding on Ruby on Rails 2.1.AudienceThis tutorial has been designed for beginners who would like to use the Ruby framework for developing database-backed web applications.PrerequisitesBefore you start Ruby on Rails, please make sure you have a basic understanding on the following subjects:∙Ruby syntax and language constructs such as blocks.∙Relational databases and SQL.∙HTML documents and CSS.Copyright & Disclaimer© Copyright 2015 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher.We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our websiteorinthistutorial,******************************************iT able of ContentsAbout the Tutorial ......................................................................................................................................Audience (i)Prerequisites (i)Copyright & Disclaimer (i)Table of Contents ...................................................................................................................................... i i 1.INTRODUCTION (1)What is Ruby? (1)Why Ruby? (1)Sample Ruby Code (2)Embedded Ruby (2)What is Rails? (3)Full Stack Framework (4)Convention over Configuration (4)Don't Repeat Yourself (DRY) (4)Rails Strengths (4)What is Rails 2.1.0? (5)2.INSTALLATION (6)Rails Installation on Windows (6)Rails Installation on Mac OS X (7)Rails Installation on Linux (7)Keeping Rails Up-to-Date (8)Installation Verification (8)How to Upgrade? (9)ii3.FRAMEWORK (10)Ruby on Rails MVC Framework (10)Representation of MVC Framework (11)Directory Representation of MVC Framework (12)4.DIR STRUCTURE (13)5.EXAMPLES (16)Workflow for Creating Rails Applications (16)Creating an Empty Rails Application (16)Starting Web Server (17)6.DATABASE SETUP (19)Configuring database.yml (19)7.ACTIVE RECORDS (21)Translating a Domain Model into SQL (21)Creating Active Record Files (21)Creating Associations between Models (22)Implementing Validations (23)8.MIGRATIONS (24)What can Rails Migration Do? (24)Create the Migrations (25)Edit the Code to Tell it What to Do (25)Run the Migration (27)Running Migrations for Production and Test Databases (27)9.CONTROLLERS (28)iiiImplementing the list Method (29)Implementing the show Method (29)Implementing the new Method (30)Implementing the create Method (30)Implementing the edit Method (31)Implementing the update Method (31)Implementing the delete Method (31)Additional Methods to Display Subjects (32)10.VIEWS (34)Creating View File for list Method (34)Creating View File for new Method (35)Creating View File for show Method (38)Creating View File for edit Method (38)Creating View File for delete Method (40)Creating View File for show_subjects Method (41)YOUTS (43)Adding Style Sheet (44)12.SCAFFOLDING (47)Scaffolding Example (47)Creating an Empty Rails Web Application (47)Setting Up the Database (47)Database Table Definition (48)The Generated Scaffold Code (49)The Controller (50)ivThe Views (53)The Migrations (53)Ready to Test (54)Enhancing the Model (56)How Scaffolding is Different? (57)13.AJAX ON RAILS (58)How Rails Implements Ajax (58)AJAX Example (59)Creating Controller (59)Creating Views (60)Adding Ajax Support (62)Creating Partial for create Method (63)14.FILE UPLOADING (65)Creating the Model (65)Creating Controller (66)Creating View (67)Files Uploaded from Internet Explorer (68)Deleting an Existing File (69)15.SENDING EMAILS (70)Setting Up the Database (70)ActionMailer – Configuration (71)Generate a Mailer (72)Creating the Controller (73)Defining Views (74)vRest for Testing (74)Sending HTML Emails using Rails (75)16.RMAGICK (77)Converting Image Formats (78)17.HTTP BASIC AUTHENTICATION (80)18.EXCEPTION HANDLING (83)Where to Log Errors? (83)19.ROUTES SYSTEM (85)Route Priority (86)Modifying the Default Route (86)The Ante-Default Route (86)The Empty Route (87)Named Routes (87)Pretty URLs (88)20.UNIT TESTING (89)Introduction (89)Rails Testing (89)Database Setup (89)Configuring database.yml: (90)Generate Migration (91)Testing Models (92)Testing the Controllers (94)Using Rake for Testing (98)vi21.QUICK REFERENCE GUIDE (99)Ruby on Rails – Rake Utility (99)Ruby on Rails – The Scripts (101)Ruby on Rails – The Plugins (102)Ruby on Rails – The Generators (102)Ruby on Rails – Model Relations (103)Association Join Models (105)Ruby on Rails – Controller Methods (106)Ruby on Rails – Layouts (107)Adding a Stylesheet (108)Ruby on Rails – Render (110)Ruby on Rails – HTML Forms (112)Checkbox Button (115)Ruby on Rails – RXML (116)Ruby on Rails – RHTML (118)Ruby on Rails – HTML Links (118)Ruby on Rails – Session and Cookies (119)Ruby on Rails – User Input Validations (120)Ruby on Rails – Maths Functions (123)Ruby on Rails – Finders (123)Ruby on Rails – Nested with-scope (125)Ruby on Rails – Callback Functions (126)viiRuby on Rails 2.1 1What is Ruby?Before we ride on Rails, let us recapitulate a few points of Ruby, which is the base of Rails.Ruby is the successful combination of:∙Smalltalk's conceptual elegance, ∙Python's ease of use and learning, and ∙ Perl's pragmatism.Ruby is∙A high-level programming language. ∙Interpreted like Perl, Python, Tcl/TK. ∙ Object-oriented like Smalltalk, Eiffel, Ada, Java.Why Ruby?Ruby originated in Japan and now it is gaining popularity in US and Europe as well. The following factors contribute towards its popularity:∙Easy to learn ∙Open source (very liberal license) ∙Rich libraries ∙Very easy to extend ∙Truly object-oriented ∙Less coding with fewer bugs ∙ Helpful communityAlthough we have many reasons to use Ruby, there are a few drawbacks as well that you may have to consider before implementing Ruby:∙ Performance Issues - Although it rivals Perl and Python, it is still an interpreted language and we cannot compare it with high-level programming languages likeC or C++.∙Threading model – Ruby does not use native threads. Ruby threads are simulated in the VM rather than running as native OS threads. 1. Ruby on Rails 2.1 – IntroductionRuby on Rails 2.1Sample Ruby CodeHere is a sample Ruby code to print "Hello Ruby".#!/usr/bin/ruby -w# The Hello Classclass Hello# Define constructor for the classdef initialize( name )@name = name.capitalizeend# Define a ruby methoddef saluteputs "Hello #{@name}!"endend# Create a new object for Hello classobj = Hello.new("Ruby")# Call ruby methodobj.saluteThis will produce the following result:Hello RubyFor a complete understanding on Ruby, please go through our Ruby TutorialEmbedded RubyRuby provides a program called ERb (Embedded Ruby), written by Seki Masatoshi. ERb allows you to put Ruby code inside an HTML file. ERb reads along, word for word, and then at a certain point, when it encounters a Ruby code, it starts executing the Ruby code.You need to know only two things to prepare an ERb document:If you want some Ruby code executed, enclose it between<%and%>.2∙If you want the result of the code execution to be printed out, as a part of the output, enclose the code between<%=and%>.Here's an example. Save the code in erbdemo.erb file. Note that a Ruby file will have an extension.rb,while an Embeded Ruby file will have an extension .erb.<% page_title = "Demonstration of ERb" %><% salutation = "Dear programmer," %><html><head><title><%= page_title %></title></head><body><p><%= salutation %></p><p>This is an example of how ERb fills out a template.</p></body></html>Now, run the program using the command-line utility erb.c:\ruby\>erb erbdemo.erbThis will produce the following result:<html><head><title>Demonstration of ERb</title></head><body><p>Dear programmer,</p><p>This is an example of how ERb fills out a template.</p></body></html>What is Rails?∙An extremely productive web-application framework.∙You could develop a web application at least ten times faster with Rails, than you could with a typical Java framework.3∙An open source Ruby framework for developing database-backed web applications.∙Your code and database schema are the configuration!∙No compilation phase required.Full Stack Framework∙Includes everything needed to create a database-driven web application using the Model-View-Controller (MVC) pattern.∙Being a full-stack framework means all the layers are built to work seamlessly with less code.∙Requires fewer lines of code than other frameworks.Convention over Configuration∙Rails shuns configuration files in favor of conventions, reflection, and dynamic run-time extensions.∙Your application code and your running database already contain everything that Rails needs to know!Don't Repeat Y ourself (DRY)DRY is a slogan you will hear frequently associated with Ruby on Rails, which means you need to code the behavior only once and you never have to write similar code in two different places. This is important because you are less likely to make mistakes by modifying your code at one place only.Rails StrengthsRails is packed with features that make you more productive, with many of the following features building on one other.Metaprogramming:Other frameworks use extensive code generation from scratch. Metaprogramming techniques use programs to write programs. Ruby is one of the best languages for metaprogramming, and Rails uses this capability well. Rails also uses code generation but relies much more on metaprogramming for the heavy lifting. Active Record:Rails introduces the Active Record framework, which saves objects to the database. The Rails version of the Active Record discovers the columns in a database schema and automatically attaches them to your domain objects using metaprogramming.Convention over configuration:Most web development frameworks for .NET or Java force you to write pages of configuration code. If you follow the suggested naming conventions, Rails doesn't need much configuration.4Scaffolding:You often create temporary code in the early stages of development to help get an application up quickly and see how major components work together. Rails automatically creates much of the scaffolding you'll need.Ajax at the core:Ajax is the technology that has become a standard to provide interactivity to websites without becoming intrusive. Ruby on Rails has a great support for Ajax technology and it is a part of the core libraries. So, when you install RoR, Ajax support is also made available to you.Built-in testing:Rails creates simple automated tests you can then extend. Rails also provides supporting code called harnesses and fixtures that make test cases easier to write and run. Ruby can then execute all your automated tests with the rake utility. Three environments:Rails gives you three default environments: development, testing, and production. Each behaves slightly differently, making your entire software development cycle easier. For example, Rails creates a fresh copy of the Test database for each test run.What is Rails 2.1.0?This is the latest version of Ruby on Rails, which has been released by the Rails core team on Saturday May 31, 2008.This version is a further improvement on RoR 2.0, which was again really a fantastic release, absolutely stuffed with great new features, loads of fixes, and an incredible amount of polish over its previous versions RoR 1.2.x.This tutorial takes you through all the important features available in the latest RoR version 2.1.0.After this tutorial, you should be able to build your website using one of the best Web 2.0 technologies called Ruby on Rails v2.1.0.5Ruby on Rails 2.1 6To develop a web application using Ruby on Rails Framework, you would need to install the following software:∙Ruby ∙The Rails framework ∙A Web Server ∙ A Database SystemWe assume that you already have installed a Web Server and Database System on your computer. You can always use the WEBrick Web Server, which comes with standard installation of Ruby. Most sites, however, use Apache or lightTPD in production. Rails works with many database systems, including MySQL, PostgreSQL, SQLite, Oracle, DB2 and SQL Server. Please refer to a corresponding Database System Setup manual to setup your database.Let's look at the installation instructions for Rails' Framework on Windows, Mac OS X, and Linux.Rails Installation on WindowsFirst, let's check to see if you already have Ruby installed. Bring up a command prompt and type C:\> ruby -v . If Ruby responds, and if it shows a version number at or above1.8.6, then type C:\> gem --version . If you don't get an error, skip to step 3. Otherwise, we'll do a fresh installation for Ruby.1. If Ruby is not installed, then download an installation package from . Follow the download link, and run the resulting installer. This is an exe like ruby186-25.exe and will be installed in a single click. You may as well install everything. It's a very small package, and you'll get RubyGems as well along with this package.2. With RubyGems loaded, you can install all of Rails and its dependencies through the command line:C:\> gem install rails --include-dependenciesThe above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies. Congratulations! You are now on Rails over Windows.NOTE: In case you face any problem with the above installation, there are chances that you may not have the latest versions of Ruby or other Gems. So just issue the following command and you will have everything updated automatically.2. Ruby on Rails 2.1 – InstallationC:\> gem updateThen try the above command with updated gems.Rails Installation on Mac OS X1.First, let's check to see if you already have Ruby installed. Bring up a commandprompt and type$ ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.6 then skip to step 3. Otherwise, we'll do a fresh installation for Ruby. To install a fresh copy of Ruby, the Unix instructions that follow should help.2.Next, you have to install RubyGems. Go to and follow thedownload link. OS X will typically unpack the archive file for you, so all you have to do is navigate to the downloaded directory and (in the Terminal application) type the following:tp> tar xzf rubygems-0.8.10.tar.gztp> cd rubygems-0.8.10rubygems-0.8.10> sudo ruby setup.rb3. Now, use RubyGems to install Rails. Issue the following command.tp> sudo gem install rails --include-dependenciesThe above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies.Congratulations! You are now on Rails over Mac OS X.NOTE:In case you face any problem with above installation, there are chances that you may not have the latest versions of Ruby or other Gems. So just issue the following command and you will have everything updated automatically.tp> sudo gem updateThen try the above command with updated gems.Rails Installation on Linux1.First, let's check to see if you already have Ruby installed. Bring up a commandprompt and type$ ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.6, then skip to step 5. Otherwise, we'll do a fresh installation for Ruby.2.Download ruby-x.y.z.tar.gz from .3.Untar the distribution, and enter the top-level directory.4.Do the usual open-source build as follows:7tp> tar -xzf ruby-x.y.z.tar.gztp> cd ruby-x.y.zruby-x.y.z> ./configureruby-x.y.z> makeruby-x.y.z> make testruby-x.y.z> make install5.Install RubyGems. Go to , and follow the download link.Once you have the file locally, enter the following at your command prompt:tp> tar -xzf rubygems-x.y.z.tar.gztp> cd rubygems-x.y.zrubygems-x.y.z> ruby setup.rb6. Now use RubyGems to install Rails. Still in the shell, issue the following command.tp> gem install rails --include-dependenciesThe above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies.Congratulations! You are now on Rails over Linux.NOTE:In case you face any problem with above installation, there are chances that you may not have the latest versions of Ruby or other Gems. So, just issue the following command and you will have everything updated automatically.tp> sudo gem updateThen try the above command with updated gems.Keeping Rails Up-to-DateAssuming you have installed Rails using RubyGems, keeping it up-to-date is relatively easy. Issue the following command:tp> gem update railsThis will automatically update your Rails installation. The next time you restart your application, it will pick up this latest version of Rails. While giving this command, make sure you are connected to the internet.Installation V erificationYou can verify if everything is setup according to your requirements or not. Use the following command to create a demo project in Rails environment.8tp> rails demoThis will create a demo rails' project using SQLite database. Note that Rails uses SQLite as its default database.We can create an application that will use MySQL database. Assuming you have MySQL database setup on your machine, issue the following command to create an application that will use MySQL database:tp> rails -d mysql demoWe will discuss the database setup part in subsequent chapters. Currently we have to check if our environment is setup properly or not. Use the following commands to run WEBrick web server on your machine:tp> cd demodemo> ruby script/server=> Rails application started on http://0.0.0.0:3000=> Ctrl-C to shutdown server; call with --help for options[2007-02-26 09:16:43] INFO WEBrick 1.3.1[2007-02-26 09:16:43] INFO ruby 1.8.2 (2004-08-24)...[2007-02-26 09:16:43] INFO WEBrick::HTTPServer-start:pid=2836.......Now open your browser and type the following address text box.http://localhost:3000You should receive a message like "Welcome aboard" or "Congratulations".How to Upgrade?If you are already running an old version of Rails, then here is the procedure to upgrade it to the latest version 2.1:1.If you want to move your application to Rails2.0, you should first move it to Rails1.2.6.2.If your application runs fine on 1.2.6 with no deprecation warnings, there's agood chance that it'll run straight up on 2.0.3.To complete the upgrade, you would have to upgrade your extractions. If you areusing pagination, you will need to install the classic_pagination plugin. If you are using Oracle, you will need to install the activerecord-oracle-adapter gem.9End of ebook previewIf you liked what you saw…Buy it from our store @ https://10。
RubyonRails开发经验分享与实践Ruby on Rails是一种常用的Web应用程序开发框架,虽然它与其他语言领域的框架有所不同,但通过合适的知识和经验,可以快速轻松地开发出高质量的Web应用程序。
在这篇文章中,我将分享我在Ruby on Rails开发中学到的一些经验和实践。
首先,无论你是需要快速开发一个小型应用程序,还是需要开发大型的复杂应用程序,了解Ruby on Rails的基本架构是非常必要的。
Ruby on Rails框架还提供了一种MVC(模型-视图-控制器)的架构,这种架构使你可以很好地管理应用程序的不同部分。
模型层,控制层和视图层负责管理数据,逻辑和UI,这使得Web应用程序的开发变得比以往任何时候都更加容易。
Ruby on Rails还带有内置的ORM(对象关系映射),使得开发人员不必担心数据库的实现细节。
其次,使用Ruby on Rails进行开发需要遵循一些最佳实践。
例如,开发人员应该确保他们遵循RESTful API原则,使应用程序具有标准的RESTful架构,Web应用程序的外部接口也会变得更加通用和易于理解。
同时,应该使用TDD(测试驱动开发)方法,确保代码的质量得到保证。
这是通过使用RSpec这样的Ruby测试框架来实现的。
通过编写测试用例,我们可以确保代码在不断变化的环境中能够保持稳定。
第三,开发人员应该更好地利用Ruby on Rails框架下的插件和Gem包。
Ruby on Rails社区为开发人员提供了很多可以直接使用的Gem包,这些包可以大大减少开发人员的工作量。
同时,社区还提供了大量的插件,这些插件可以方便地扩展应用程序的实现功能。
例如,像Devise这样的插件可以很好地帮助管理用户的身份验证和访问控制。
最后,成功的Ruby on Rails开发不仅仅只是有良好的技术知识,还需要开发人员具备强大的沟通能力和创造力。
开发人员应该能够与其他开发人员及客户进行高效沟通,确保需求的准确理解和以高效的方式完成开发任务。