首先声明:本文不是ruby on rails的入门教程
入门教程可以参考:
http://www.tutorialspoint.com/ruby-on-rails/rails-controllers.htm
http://guides.rubyonrails.org/active_record_basics.html
http://guides.rubyonrails.org/getting_started.html#saving-data-in-the-controller
本文仅列举入门过程中容易犯的错误
ruby版本:
ruby -v
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin15]
rails版本:
rails -v
Rails 4.2.6
gem -v
2.5.1
rake --version
rake, version 11.1.2
(1)配置文件冒号后面缺少空格
注意:冒号后面需要空格
(2)获取表单参数
以为
- params[article]
可以获取表单提交的参数
article前面要加上冒号
正确:
- params[:article]
(3)持久化表单参数
最开始以为:
- # 增加,持久化到数据库
- def create
- articles = Article.create(params[:article])
- render plain: params[:article].inspect
- end
结果报错:
ActiveModel::ForbiddenAttributesError
正确的:
- # 增加,持久化到数据库
- def create
- articles = Article.create(params.require(:article).permit(:title, :text))
- render plain: params[:article].inspect
- end
范例:
- def create
- @book = Book.new(book_params)
- if @book.save
- redirect_to :action => 'list'
- else
- @subjects = Subject.all
- render :action => 'new'
- end
- end
- def book_params
- params.require(:books).permit(:title, :price, :subject_id, :description)
- end
(4)传递数据到view
以为这样就可以把model传递到view:
- # 条件查询
- def show
- id=params[:id]
- article=Article.find_by(id: id)
- end
article前面应该加上at符号
正确的:
- # 条件查询
- def show
- id=params[:id]
- @article=Article.find_by(id: id)
- end
添加记录的表单(app/views/articles/new.html.erb):
- <h1>New Article</h1>
- <div>
- <%= form_for :article, url: articles_path do |f| %>
- <p>
- <%= f.label :title %><br>
- <%= f.text_field :title %>
- </p>
- <p>
- <%= f.label :text %><br>
- <%= f.text_area :text %>
- </p>
- <p>
- <input type="text" name="username">
- </p>
- <p>
- <%= f.submit %>
- </p>
- <% end %>
- </div>
注意:等号后面需要空格
查询结果的显示页面(app/views/articles/show.html.erb):
- <div>查询结果:</div>
- <div>
- <ul>
- <li>
- <label for="">title:</label>
- <label for=""> <%= @article.title %> </label>
- </li>
- <li>
- <label for="">text:</label>
- <label for=""> <%= @article.text %> </label>
- </li>
- </ul>
- </div>
(5)启动服务
powder link
或者:
./bin/rails server(端口默认是:3000)
停止服务:powder unlink
(6)执行migrate
功能:创建数据表
rake db:migrate
rake db:migrate VERSION=20080906120000