Rails Basics(Rails基础)

本文介绍Ruby on Rails(RoR)框架的基本概念和发展历程,并通过逐步搭建一个简单的“Hello World”应用来演示其主要组成部分,包括模型(Model)、视图(View)、控制器(Controller),以及数据库迁移等核心功能。
本文翻译自SUN官方文档

What is and Why Ruby on Rails (RoR)? 
 
What Is “Ruby on Rails”?
A full-stack MVC web development framework
一个MVC的web开发框架
Written in Ruby
Ruby编写
First released in 2004 by David Heinemeier Hansson
由David Heinemeier Hansson在2004年发布第一个版本
Gaining popularity
更加流行
 
 “Ruby on Rails” MVC

 

“Ruby on Rails” Principles
“Ruby on Rails”的准测
Convention over configuration
约定更重于配置
  Why punish the common cases?
    Encourages standard practices
    鼓励标准化
    Everything simpler and smaller
    每件事情更加简单而小型化
  Don’t Repeat Yourself (DRY)
    Framework written around minimizing repetition
    这个框架减少重复劳动
    Repetitive code harmful to adaptability
    重复性代码有害适用性
  Agile development environment
    No recompile, deploy, restart cycles
    没有编译,部署,重启环节
    Simple tools to generate code quickly
    简单的工具高效产生代码
    Testing built into the framework
    由测试驱动


Step By Step Process of Building “Hello World” Rails Application
一步一步搭建“Hello World”的Rails应用
Steps to Follow:
  1. Create “Ruby on Rails” project - Rails generates directory structure    Rails自动产生目录结构
  2. Create Database (using Rake)    自动创建数据库
  3. Create Models (through Rails Generator)    自动创建模型
  4. Create Database Tables (using Migration)    自动创建数据表
  5. Create Controllers (through Rails Generator)    自动创建控制器
  6. Create Views    创建视图
  7. Set URL Routing - Map URL to controller and action    映射URL到控制器和action

Demo: Building “Hello World” Rails Application Step by Step.

1. Create “Ruby on Rails” Project
创建“Ruby on Rails”工程
The directory structure along with boilerplate files of the application is created
目录结构被自动创建


Directory Structure of a Rails Application
When you ask NetBeans to create a Rails project  - internally NetBeans uses the rails' helper script -, it creates the entire directory structure for your application.
netbeans会自动创建Rails的目录结构
    The boiler plate files are also created
    The names of the directories and files are the same for all Rails projects
Rails knows where to find things it needs within this structure, so you don't have to tell it explicitly.
Rails知道如何从这种结构里找到它需要的东西,你不必明确指明。

Directory Structure of a Rails Application
app: Holds all the code that's specific to this particular application.
app:控制这个项目专属的代码
  1. app/controllers: Holds controllers that should be named like hello_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base.    app/controllers:控制器应该被命名如hello_controller.rb,这样就能自动映射URL。
  2. app/models: Holds models that should be named like message.rb. Most models will descend from ActiveRecord::Base.    app/models:模型应该被命名为message.rb。
  3. app/views: Holds the template files for the view that should be named like hello/say_hello.rhtml for the HelloController#say_hello action.     app/views:视图的模板文件应该被命名为hello/say_hello.rhtml
  4. app/views/layouts: Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout :default</tt> and create a file named default.rhtml. Inside default.rhtml, call <% yield %> to render the view using this layout.
  5. app/helpers: Holds view helpers that should be named like hello_helper.rb. These are generated for you automatically when using script/generate (Generator) for controllers. Helpers can be used to wrap functionality for your views into methods.
config: Holds configuration files for the Rails environment, the routing map, the database, and other dependencies.
config:控制Rails环境的配置文件
config/environments
config/initializers
boot.rb
database.yml
environment.rb
routes.rb


Learning Point: Environments

What is an Environment?
Rails provides the concept of environments - development, test, production
Rails提供环境的概念 - 开发,测试,产品
As a default, different database is going to be used for different environment.
默认情况下,不同的数据将被用于不用的环境、
    Therefore each environment has its own database connection settings.
    因此,不同的环境有自己独立数据联接设置
It is easy to add custom environments
添加环境是很方便的
    For example, staging server environment
    例如,添加server环境
Rails always runs in only one environment
Rails只能在一个环境里运行
    Dictated by ENV['RAILS_ENV'] (same as RAILS_ENV)

config/database.yml
  1. development:
  2.   adapter: mysql
  3.   encoding: utf8
  4.   database: helloname_development
  5.   username: root
  6.   password:
  7.   host: localhost
  8. test:
  9.   adapter: mysql
  10.   encoding: utf8
  11.   database: helloname_test
  12.   username: root
  13.   password:
  14.   host: localhost

2. Create Database using “Rake”
Creating Database
    Creating and dropping of databases are done using “Rake”    用Rake创建和删除数据库


After create rake task is performed, <project_name>_development database, for example, helloworld_development is created


Learning Point: What is Rake?
What is “Rake”?
  1. Rake is a build language for Ruby.
  2. Rails uses Rake to automate several tasks such as creating and dropping databases, running tests, and updating Rails support files.
  3. Rake lets you define a dependency tree of tasks to be executed
How does “Rake” Work?
  1. Rake tasks are loaded from the file Rakefile
  2. Rails rake tasks are under <project-name>/lib/tasks
  3. You can put your custom tasks under lib/tasks
Useful Rake Tasks
db:migrate
db:sessions:create
doc:app
doc:rails
log:clear
rails:freeze:gems
rails:freeze:edge
rails:update
:test
:stats


3. Create a Model through “Generator”
What is a Model?
    In the context of MVC pattern, a Model represents domain objects such as message, school, product, etc.  A model has attributes and methods.
        The attributes represents the characteristics of the domain object, for example, a message model might have length, creator as attributes.  
        The methods in a model contains some business logic.  
    Most models have corresponding database tables.  For example, a message model will have messages table.
    Most model classes are ActiveRecord type

Creating a Model using Generator



Files That Are Created
app/models/message.rb (Model file)
  1. Models/messages.rb in logical view
  2. A file that holds the methods for the Message model.
test/unit/message_test.rb
  1. Unit Tests/message_test.rb in logical view
  2. A unit test for checking the Message model.
test/fixtures/messages.yml
  1. Test Fixtures/messages.yml in logical view
  2. A test fixture for populating the model.
db/migrate/migrate/001_create_messages.rb
  1. Database Migrations/migrate/001_create_messages.rb in logical view
  2. A migration file for defining the initial structure of the database.

Model Class Example
Message mode in messages.rb file
  1. class Message < ActiveRecord::Base
  2. end


Learning Point: What is Generator?
What is “Generator”?
You can often avoid writing boilerplate code by using the built-in generator scripts of Rails to create it for you.
模板的代码可以由Rails脚本完成
This leaves you with more time to concentrate on the code that really matters--your business logic.
这可以使你将更多的精力放在那些真正有意义的业务逻辑代码上

Leaning Point:What is Rails Console?
The Rails console gives you access to your Rails Environment, for example, you can interact with the domain models of your application as if the  application is actually running.
    Things you can do include performing find operations or creating a new active record object and then saving it to the database.
A great tool for impromptu testing
NetBeans runs a script to start Rails Console


Leaning Point: What is Rails Script?
Script
NetBeans runs Rails Script internally
    You can run the Script at the commandline
Useful scripts
console
generate
plugin
server


4. Create Database Tables using Migration
You are going to create a database table (in a previously created database) through migration
    You also use migration for any change you are going to make in the schema - adding a new column, for example
When you create a Model, the first version of the migration file is automatically created
    db/migrate/migrate/001_create_messages.rb, which defines initial structure of the table
  1. class CreateMessages < ActiveRecord::Migration
  2.   def self.up
  3.     create_table :messages do |t|
  4.       t.string :greeting
  5.       t.timestamps
  6.     end
  7.   end
Performing Migration


Leaning Point: What is Migration?
Migrations can manage the evolution of a schema.
It's a solution to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to push that change to other developers and to the production server.
With migrations, you can describe the transformations in self-contained classes that can be checked into version control systems and executed against another database that might be one, two, or five versions behind. 

5. Create a Controller
  1. Action Controllers are the core of a web request in Rails.
  2. They are made up of one or more actions that are executed on request and then either render a template or redirect to another action.
  3. An action is defined as a public method on the controller, which will automatically be made accessible to the web-server through Rails Routes.
  4. You are going to create a controller using Generator


Example: HelloController
Controller contains actions, which are defined with def
  1. class HelloController < ApplicationController
  2.   def say_hello
  3.     @hello = Message.new(:greeting => "Hello World!")
  4.   end
  5. end


6. Write a View
What is a View?
  1. View is represented by a set of templates that get displayed. 
  2. Templates share data with controllers through mutually accessible variables. 
  3. A template can be either in the form of *.rhtml or *.erb file.  -  The *.erb file is searched first by Rails. If there is no *.erb file, then *.rhtml file is used.
  4. RHTML file is created under the directory of /app/views/<controller>

  1. say_hello.rhtml
  2. My greeting message is <%= @hello.greeting %>
  3. <br/>
  4. The current time is <%= Time.now %>


7. Set URL Routing
URL Routing
The Rails routing facility is pure Ruby code that even allows you to use regular expressions.
    Because Rails does not use the web server's URL mapping, your custom URL mapping will work the same on every web server.
    configuration/routes.rb file contains the routing setting

routes.rb
  1. ActionController::Routing::Routes.draw do |map|
  2.   
  3.   map.root :controller => "hello"
  4.   # Install the default routes as the lowest priority.
  5.   map.connect ':controller/:action/:id'
  6.   map.connect ':controller/:action/:id.:format'
  7. end

内容概要:本文详细介绍了一种基于Simulink的表贴式永磁同步电机(SPMSM)有限控制集模型预测电流控制(FCS-MPCC)仿真系统。通过构建PMSM数学模型、坐标变换、MPC控制器、SVPWM调制等模块,实现了对电机定子电流的高精度跟踪控制,具备快速动态响应和低稳态误差的特点。文中提供了完整的仿真建模步骤、关键参数设置、核心MATLAB函数代码及仿真结果分析,涵盖转速、电流、转矩和三相电流波形,验证了MPC控制策略在动态性能、稳态精度和抗负载扰动方面的优越性,并提出了参数自整定、加权代价函数、模型预测转矩控制和弱磁扩速等优化方向。; 适合人群:自动化、电气工程及其相关专业本科生、研究生,以及从事电机控制算法研究与仿真的工程技术人员;具备一定的电机原理、自动控制理论和Simulink仿真基础者更佳; 使用场景及目标:①用于永磁同步电机模型预测控制的教学演示、课程设计或毕业设计项目;②作为电机先进控制算法(如MPC、MPTC)的仿真验证平台;③支撑科研中对控制性能优化(如动态响应、抗干扰能力)的研究需求; 阅读建议:建议读者结合Simulink环境动手搭建模型,深入理解各模块间的信号流向与控制逻辑,重点掌握预测模型构建、代价函数设计与开关状态选择机制,并可通过修改电机参数或控制策略进行拓展实验,以增强实践与创新能力。
根据原作 https://pan.quark.cn/s/23d6270309e5 的源码改编 湖北省黄石市2021年中考数学试卷所包含的知识点广泛涉及了中学数学的基础领域,涵盖了实数、科学记数法、分式方程、几何体的三视图、立体几何、概率统计以及代数方程等多个方面。 接下来将对每道试题所关联的知识点进行深入剖析:1. 实数与倒数的定义:该题目旨在检验学生对倒数概念的掌握程度,即一个数a的倒数表达为1/a,因此-7的倒数可表示为-1/7。 2. 科学记数法的运用:科学记数法是一种表示极大或极小数字的方法,其形式为a×10^n,其中1≤|a|<10,n为整数。 此题要求学生运用科学记数法表示一个天文单位的距离,将1.4960亿千米转换为1.4960×10^8千米。 3. 分式方程的求解方法:考察学生解决包含分母的方程的能力,题目要求找出满足方程3/(2x-1)=1的x值,需通过消除分母的方式转化为整式方程进行解答。 4. 三视图的辨认:该题目测试学生对于几何体三视图(主视图、左视图、俯视图)的认识,需要识别出具有两个相同视图而另一个不同的几何体。 5. 立体几何与表面积的计算:题目要求学生计算由直角三角形旋转形成的圆锥的表面积,要求学生对圆锥的底面积和侧面积公式有所了解并加以运用。 6. 统计学的基础概念:题目涉及众数、平均数、极差和中位数的定义,要求学生根据提供的数据信息选择恰当的统计量。 7. 方程的整数解求解:考察学生在实际问题中进行数学建模的能力,通过建立方程来计算在特定条件下帐篷的搭建方案数量。 8. 三角学的实际应用:题目通过在直角三角形中运用三角函数来求解特定线段的长度。 利用正弦定理求解AD的长度是解答该问题的关键。 9. 几何变换的应用:题目要求学生运用三角板的旋转来求解特定点的...
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值