2012-09-19 51 views
6

我是新來的Rails中插入數據庫記錄,我想學習這種技術,所以請原諒如果問題是愚蠢的。的Rails 3:如何使用Rails

我使用Rails 3。

請讓我知道我可以在數據庫中插入一條記錄。

我uisng 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 

這是在我的視圖文件\應用\ 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

請讓我知道我可以在數據庫中插入一條記錄?你應該使用的

+0

作爲答案將是非常大的顯示完整的程序,請按照Rails入門。它將幫助您瞭解Rails如何工作。 http://guides.rubyonrails.org/getting_started.html – HungryCoder

+0

@Preethi Jain:有什麼幫助你嗎? – Samiron

回答

12

你瞭解RESTful嗎?我假設你知道它,除非你能在導軌導向找到它(在表單標籤,你必須添加@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

+0

非常感謝。 – Pawan

+0

關於這個創建的唯一的事情是它不會自動生成服務器ID,並會抱怨ID爲零。 –

7

第一軌道的輔助方法form_for產生構建形式。按照this link。在您的模型中,您應該將學生數據作爲名爲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 

獲取更多的見解here

一些最有用的鏈接:

2

Rails是一個複雜的框架。這並不意味着它很難(即使有時),但是有很多話題需要掌握。你一定要閱讀一個教程,以幫助你開始:金條軌道指南"Getting Started"是一個非常體面的方式讓自己沉浸在軌道。

之後,你會有你的問題的答案,但也有更多的答案......也許更多的問題。