如何从Ruby上的数据库中读取数据

时间:2012-04-26 14:50:14

标签: ruby-on-rails ruby ruby-on-rails-3

def add
    if params[:note_add] == "Add"
      Note.create({:user_id => @user["id"], :note_type => params[:type], :text => params[:note_text], :lng => params[:lng], :lat => params[:lat]})
    end
  end

我是Ruby on Rails的新手,我正在尝试从数据库中获取数据。我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

如果你使用像MySQL,Postgres或其他的关系数据库,你应该使用RoR带来的Active Record。它是一个ORM,提供了与DB交互的大量功能,似乎你已经在使用它了。要查询数据,请在指南中查看此页面。 http://guides.rubyonrails.org/active_record_querying.html

一些例子

Note.find(1) #get note with id=1
Note.find_by_note_type("sometype") #gets first found with note_type="sometype" (I think so)
Note.where("note_type = ?", "sometype") #gets all notes that have note_type="sometype"

答案 1 :(得分:0)

有很多方法可以做到这一点...... 您可以查看https://github.com/ryanb/railscasts-episodes/tree/master/episode-216它是http://railscasts.com/episodes/216-generators-in-rails-3 rails cast的来源。 在那里,您可以看到使用支架如何轻松地使用您的数据生成CRUD操作。它将帮助您理解Rails的主要思想。

答案 2 :(得分:0)

Note.find()Note.all

假设您已经创建了Note模型。在控制台rails console

中试用