在ActiveRecord中使用多个表

时间:2014-03-07 22:17:22

标签: ruby activerecord sinatra

我正在尝试创建一个api,但我只能找到使用单个表的示例。这是我发现我要复制的一个例子,但是有更多的表。

http://mopsled.com/2013/01/building-restful-api/

此代码也会在每次运行时创建数据库。你如何设置它以便它只使数据库一次。

提前致谢!

1 个答案:

答案 0 :(得分:0)

假设您有两个名为albumstracks的表,您只想创建一次,那么您的两个请求都在这些代码行中:

ActiveRecord::Schema.define do
  unless ActiveRecord::Base.connection.tables.include? 'albums'
    create_table :albums do |table|
      table.column :title,     :string
      table.column :performer, :string
    end
  end

  unless ActiveRecord::Base.connection.tables.include? 'tracks'
    create_table :tracks do |table|
      table.column :album_id,     :integer
      table.column :track_number, :integer
      table.column :title,        :string
    end
  end
end

您可以通过reading this article.

获取更多信息