基于RailsGuides的学习心得
一.初始化页面的改变
1.在终端:rails new demo -d mysql
登录数据库 填写密码
(在demo目录下) rails db:create
2.启动服务器:rails s
访问 http://localhost:3000
3.通过创建控制器和视图进行页面的显示
rails g controller Welcome index
此时创建控制器Welcome,包含了index动作
4.在编辑器中打开 config/routes.rb 文件进行路由配置
get ‘welcome/index’ 此时是http://localhost:3000/welcome/index的访问指向index动作
root ‘welcome#index’ 对根路径的访问指向index动作
5.此时可以发现再次访问http://localhost:3000,根目录已改变。
二.创建一个Article 资源
1.首先在路由文件中声明resources :articles
2.如果要用一个页面来显示文章,就需要一个控制器来控制,所以此时建立一个控制器。
rails g controller Articles
此时会生成一个文件
class ArticlesController < ApplicationController
end
此时在这个类中定义动作,这些动作再通过视图进行提现。
3.类中的动作和视图一一对应
class ArticlesController < ApplicationController
def new
end
end
此时在view目录下新建一个new.html.erb文件,可以尝试添加以下代码
<%= form_for :article do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
4.如果将第一句话改成
<%= form_for :article, url: articles_path do |f| %>
articles_path 把表单指向和 articles 前缀相关联的 URI 模式。默认情况下,表单会向这个路由发起 POST 请求。这个路由和当前控制器 ArticlesController 的 create 动作相关联。
5.添加create动作
因为此时并没有create动作,所以要在类中添加
def create
render plain: params[:article].inspect
end
此时提一下render和redirect_to的区别
render:简单的页面渲染,跳转到某个页面,但是不会发出请求,只根据函数参数渲染页面,不会执行action函数,不会重新加载服务器中的数据
redirect_to:(相当于刷新)发送请求重定向页面,可以指定controller和action,会执行对应的action,重新加载服务器数据,不保留页面中原有的数据。
6.创建模型
因为我们要存储Article的title和text ,我们需要把数据存储在数据库,所以要创建模型
rails g model Article title:string text:text
这个模型里面有两个属性。
在 Rails 中,模型使用单数名称,对应的数据库表使用复数名称。
7.运行迁移
Rails 使用 rake 命令运行迁移,把数据迁移到数据库
rails db:migrate
只要创建模型,就需要进行迁移,来存储我们的数据。
8.在控制器中保存数据
def create
@article=Article.new(params[:article])
@article.save
redirect_to @article
end
但是这样一写就把所有参数都传过去了,这样不太安全,所以我们就换一种写法,只传title和text
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
private
def article_params
params.require(:article).permit(:title, :text)
end
9.显示文章
想要显示文章,就要在view里新建一个show.html.erb,但是首先我们要先建一个控制器,即在类中进行动作的添加。
def show
@article = Article.find(params[:id])
end
然后在show.html.erb中写入
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.text %>
</p>
现在访问 http://localhost:3000/articles/new
就可以新建文章了。