我是Rails的新手,我正在尝试学习这项技术,所以请原谅我的问题是否愚蠢.
我正在使用Rails 3.
请让我知道如何在数据库中插入记录.
我是ugng postgresql,下面是学生表的表结构.
SELECT column_name FROM information_schema.columns WHERE table_name ='Students';
column_name
-------------
id
name
age
description
(4 rows)
Run Code Online (Sandbox Code Playgroud)
这是我的Controller文件student_controller.rb
class StudentController < ApplicationController
def new
end
end
Run Code Online (Sandbox Code Playgroud)
这是我的模型文件student.rb
class Student < ActiveRecord::Base
end
Run Code Online (Sandbox Code Playgroud)
这是我在\ app\views\student \new.html.erb下的视图文件
<h1>BookController#new</h1>
<form>
Id: <input type="text" name="id" /><br />
Last Name: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
Desciption: <input type="text" name="description" />
</form>
Run Code Online (Sandbox Code Playgroud)
当我访问 http://localhost:3000/student/new
请让我知道如何在数据库中插入记录?
duy*_*hoa 13
你了解RESTful吗?我假设您知道它,除非您可以在rails指南中找到它(在表单标签中,您必须添加@student,:action => :new, :method => :post)要添加新记录,只需键入Student.create(:name=> "a", :age => 2)
此语句由2个句子组成
object = Student.new(:name => "a", :age => 2)
object.save
Run Code Online (Sandbox Code Playgroud)
我建议你改用rails generate scaffold Student这样的东西.然后,在控制器,视图中读取这些生成代码,你会非常深入地理解!:) P/s:我也是业余爱好者:D
首先,您应该使用rails helper方法form_for生成构建表单.点击此链接.在您的模型中,您应该将您的学生数据作为名为密钥的哈希值接收student.所以在你的控制器中它就像
def create
@student = Student.new(params[:student])
respond_to do |format|
.. ... ...
#handle the response
end
end
Run Code Online (Sandbox Code Playgroud)
这是一个comments_controller.rb快速查看的示例文件.https://gist.github.com/3748175
但最重要的是!!
由于您对这项技术完全陌生,我建议制作一个示例rails应用程序的脚手架并完成自动生成的代码.
# run this command in your command line to generate the codes
rails generate scaffold Student name:string age:integer description:text
Run Code Online (Sandbox Code Playgroud)
在这里获得更多见解.
一些最有用的链接:
| 归档时间: |
|
| 查看次数: |
32527 次 |
| 最近记录: |