11

我是 Rails 新手,我正在努力学习这项技术,所以如果问题很愚蠢,请原谅。

我正在使用 Rails 3 。

请让我知道如何在数据库中插入记录。

我正在使用 postgresql,下面是学生表的表结构。

SELECT column_name FROM information_schema.columns WHERE table_name ='Students';

 column_name
-------------
 id
 name
 age
 description
(4 rows)

这是我的控制器文件 student_controller.rb

class StudentController < ApplicationController

  def new
  end

end

这是我的模型文件 student.rb

class Student < ActiveRecord::Base

end

这是我在 \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>

当我访问http://localhost:3000/student/new

请让我知道如何在数据库中插入记录?

4

3 回答 3

15

你了解 RESTful 吗?我假设您知道它,除非您可以在 rails guide 中找到它(在表单标签中,您必须添加@student,:action => :new, :method => :post)要添加新记录,只需键入Student.create(:name=> "a", :age => 2) 此语句由 2 个句子组成

object = Student.new(:name => "a", :age => 2)
object.save

我建议您rails generate scaffold Student改用创建这样的所有内容。然后,在控制器,视图中阅读这些生成代码,您会非常深刻地理解!:) P/s:我也是业余爱好者:D

于 2012-09-19T10:17:24.353 回答
7

首先,您应该使用 rails helper 方法form_for来生成构建表单。按照这个链接。在您的模型中,您应该将学生数据作为散列接收到名为student. 所以在你的控制器中它会像

def create
    @student = Student.new(params[:student])
    respond_to  do |format|
          .. ... ...
          #handle the response
    end
end

这是一个快速浏览的示例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

在这里获得更多见解。

一些最有用的链接:

于 2012-09-19T07:25:47.710 回答
2

Rails 是一个复杂的框架。这并不意味着它很难(即使有时很难),而是有很多主题可以让你掌握。您绝对应该阅读一个教程来帮助您入门:官方 Rails 指南“入门”是让自己沉浸在 Rails 中的一种非常体面的方式。

在那之后,你会得到你的问题的答案,但也有更多的答案……可能还有更多的问题。

于 2012-09-19T07:33:13.140 回答